简体   繁体   English

如何在std :: map容器中修改键值

[英]How to modify key values in std::map container

Given 给定

std::map<int,std::string> myMap;
fillMyMapWithStuff(myMap);

// modify key values - I need to add a constant value to each key
for (std::map<int,std::string>::iterator mi=myMap.begin(); mi != myMap.end(); ++mi)
{
    // ...
}

Whats a good way apply some re-indexing? 什么是应用一些重新索引的好方法? Must I remove the old entry and add a new one with the new key and old value? 我必须删除旧条目并添加具有新键和旧值的新条目吗?

Looks like you are better off building a new map and swapping it afterward. 看起来您最好构建一个新地图,然后再交换它。 You'll have only n insert operations instead of n deletions and n insertions. 您将只有n插入操作,而不是n删除和n插入。

Yes, you have to remove the old entry and add a new one with the new key. 是的,您必须删除旧条目并使用新密钥添加一个新条目。 Keys are not modifiable. 密钥不可修改。

If you were modifying only one or a few elements, you could do it efficiently by hinting map::insert with the position of the new element. 如果仅修改一个或几个元素,则可以通过提示map::insert并包含新元素的位置来有效地进行修改。 Since your new keys are sure to be located somewhere after the old keys, you can hint with the iterator that points at the old element. 由于新的密钥是确保旧密钥 ,可将位于某处,你可以用迭代暗示在旧元素点。 However, you'd have to take care not to re-evaluate the freshly-inserted keys (by iterating end to front for example), and in case of modifying the entire map, it's more efficient to just build a new one. 但是,您必须注意不要重新评估新插入的键(例如,从头到尾进行迭代),并且在修改整个地图的情况下,仅构建一个新的键会更有效。

Yes, you must. 是的,你必须。 The key is const while it is in the map. 键在地图中时是const。

I think you'll have to construct a new map. 我认为您必须构建一张新地图。 If you delete and add new keys within the loop, it might destroy the integrity of iterating over the set of old keys, and not touching the just-inserted keys. 如果在循环中删除并添加新键,则可能会破坏在一组旧键上进行迭代的完整性,并且不会触摸刚刚插入的键。 (Unless you know how your keys are distributed and put your own logic in there.) (除非您知道密钥的分配方式,并在其中放置自己的逻辑。)

std::map<int,std::string> myMap;
fillMyMapWithStuff(myMap);

std::map<int,std::string> newMap;

// modify key values - I need to add a constant value to each key
for (std::map<int,std::string>::iterator mi=myMap.begin(); mi != myMap.end(); ++mi)
{
    newMap[mi->first] = mi->second;
}

There's one more option. 还有一个选择。 If this operation is a significant feature of your collection, and performance is important, you can avoid copying the map altogether. 如果此操作是集合的重要功能并且性能很重要,则可以避免完全复制地图。 You can create a class overloading operator[] , as well as other accessors and mutators, and add the current shift of the key value. 您可以创建一个类重载operator[]以及其他访问器和修改器,并添加键值的当前移位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM