gpt4 book ai didi

c++ - std::map::iterator 是否返回值的拷贝或值本身?

转载 作者:IT老高 更新时间:2023-10-28 12:59:14 25 4
gpt4 key购买 nike

我正在尝试在 map 中创建 map :

typedef map<float,mytype> inner_map;
typedef map<float,inner_map> outer_map;

我能否在内部 map 中放一些东西,或者 iterator::second 返回一个拷贝?

STL_pair.h 建议后者:

74: _T2 second;          ///< @c second is a copy of the second object

但我的测试程序运行良好,代码如下:

it = my_map.lower_bound(3.1415);
(*it).second.insert(inner_map::value_type(2.71828,"Hello world!");

那么真相在哪里?这是不是拷贝?

最佳答案

我想为使用 C++11 迭代器的人添加此问题的后续答案...

以下代码:

std::map<std::string, std::string> m({{"a","b"},{"c","d"}});
for (auto i : m)
{
std::cout << i.first << ": " << i.second << std::endl;
}

确实复制键和值,因为默认情况下“auto”是一个值,而不是 const 引用(至少它是 clang 3.1 的行为方式)。

另外,代码:

std::map<std::string, std::string> m({{"a","b"},{"c","d"}});
for (const std::pair<std::string,std:string>& i : m)
{
std::cout << i.first << ": " << i.second << std::endl;
}

复制键和值,因为正确的代码应该是:

std::map<std::string, std::string> m({{"a","b"},{"c","d"}});
for (const auto& i : m)
{
std::cout << i.first << ": " << i.second << std::endl;
}

std::map<std::string, std::string> m({{"a","b"},{"c","d"}});
for (const std::pair<const std::string,std:string>& i : m)
{
std::cout << i.first << ": " << i.second << std::endl;
}

关于c++ - std::map::iterator 是否返回值的拷贝或值本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377434/

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