gpt4 book ai didi

c++引用复制麻烦(STL对)

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:18 25 4
gpt4 key购买 nike

我很难实现这样的事情:

int a = 5;
int& b = a;
pair <int, int> test;
test.first = b;
a = 1000;

test.first显然,值不会改变,但我希望它改变,所以我正在尝试创建 pair <int&, int&> ,但我不能因为编译器。

我的目标是获得 test.first改变了,我该如何实现它(不使用 int* 指针,是的)?

最佳答案

在 C++11 中,您可以使用 reference_wrapper。你的代码会变成

#include <functional>
int a = 5;
auto b = ref(a);
b.get() = 3;
cout<<a<<endl;
pair <reference_wrapper<int>, int> test(b, 0);
a = 1000;
cout<<test.first<<endl;

关于c++引用复制麻烦(STL对),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com