gpt4 book ai didi

c++ - 修改 C++ unordered_map 中复杂类型的值

转载 作者:行者123 更新时间:2023-11-30 01:44:25 24 4
gpt4 key购买 nike

我试图理解为什么使用 operator[]unordered_map当我尝试使用 [] 修改值时,在 C++ 中给出了不同的结果直接与将值存储在临时对象中。这是一个例子:

unordered_map<int,vector<int>> map;
map.emplace(0, vector<int>(10, 1) );

map[0][0] = 2; // this works
cerr << map[0][0] << endl; // prints out 2 - as expected

auto foo = map[0];
foo[1] = 3; // this does not work -- the value in map[0][1] is still 1
cerr << map[0][1] << endl; // prints out 1, expected: 3

我的理解是map[0]应该返回对关联值的引用,而不是它的拷贝,但似乎 foo是自更改为 foo 后的拷贝是短暂的。我错过了什么?

最佳答案

从 map[0] 的返回类型构造一个新变量(拷贝)foo:

auto foo = map[0];

使 foo 的类型与 map[0] 返回的完全相同,即使它是一个引用:

decltype(auto) foo = map[0];

引用从 map[0] 的返回类型中删除任何引用说明符所产生的类型:

auto& foo = map[0];

对从 map[0] 的返回类型中删除任何引用说明符和 const 说明符所产生的类型进行常量引用:

auto const& foo = map[0];

关于c++ - 修改 C++ unordered_map 中复杂类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294660/

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