在 std::map 中替换现有条目并添加新条目

Chr*_*ris 0 c++ iterator stl stdmap

考虑以下片段:

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;
}
Run Code Online (Sandbox Code Playgroud)

我认为使用从 insert 返回的迭代器是最有效的版本。

然而,起初,我只是认为分配迭代器只能正常工作(请注意,我不再在这里取消引用迭代器)。

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;
Run Code Online (Sandbox Code Playgroud)

我知道它已经过时了,因为我已经匹配了密钥并且只关心值。发生此错误只是因为键是 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;
Run Code Online (Sandbox Code Playgroud)

这是我实际上不明白的事情。std::map 中迭代器的分配应该如何表现?虽然我已经编写 C++ 几年了,但我从未遇到过我为任何容器这样做的情况。在一些研究中,我没有找到很多关于一般分配迭代器的信息。

最后会不会有一种更优雅的方式来做我想要实现的目标(使用 C++11 特性,也许是 C++14)?

Som*_*ude 5

为什么要弄得这么复杂?为什么不简单

map[itSecond->first] = itSecond->second;
Run Code Online (Sandbox Code Playgroud)

如果它们的键存在,则数据将被更改。如果密钥不存在,则将插入该对。


也不要忘记value_typeof std::mapstd::unordered_map就此而言)是std::pair<const Key, T>.

由于键是常量,您不能简单地分配或复制迭代器,您只能分配或复制值。