【发布时间】:2018-12-07 07:41:26
【问题描述】:
考虑以下sn-p:
MapT map;
map["A"] = 1;
map["B"] = 2;
map["C"] = 3;
map["D"] = 4;
map["E"] = 5;
MapT mapSecond;
mapSecond["A"] = 10;
mapSecond["B"] = 20;
mapSecond["C"] = 30;
mapSecond["X"] = 4;
mapSecond["Y"] = 5;
MapT::const_iterator itSecond = mapSecond.begin();
MapT::iterator it = map.begin();
for (; itSecond != mapSecond.end(); ++itSecond)
{
std::pair<MapT::iterator, bool> pair = map.insert(std::make_pair(itSecond->first, itSecond->second));
if (!pair.second)
{
pair.first->second = itSecond->second;
}
}
for (; it != map.end(); ++it)
{
std::cout << it->first << " " << it->second << std::endl;
}
我假设使用从插入返回的迭代器是最有效的版本。
但一开始,我只是认为分配迭代器只能正常工作(请注意,我不再在这里取消引用迭代器)。
1.)
// assigning the dereferenced iterator (i.e.: the underlying std::pair)
// resulting in no match for binary '=' operator for const std::string
*pair->first = *itsecond;
我知道它已经过时了,因为我已经匹配了键并且只关心值。发生此错误仅是因为密钥是 const std::string 如果我没有完全失去理智:D
2.)
// assigning the iterator itself
// does not compile as long as itSecond is of type const_iterator ?
// does nothing in case itSecond is of type iterator
pair.first = itSecond;
这是我实际上不明白的事情。 std::map 中迭代器的赋值应该如何表现? 尽管我已经做了几年 C++ 编程,但我从来没有遇到过我为任何容器这样做的场景。在一些研究中,我没有找到很多关于分配迭代器的信息。
最后是否会有一种更优雅的方式来实现我想要实现的目标(使用 C++11 功能,也许是 C++14)?
【问题讨论】: