How to modify key values in std::map container

2020-02-10 07:45发布

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?

标签: c++ stdmap
5条回答
Anthone
2楼-- · 2020-02-10 08:24

Yes, you must. The key is const while it is in the map.

查看更多
Bombasti
3楼-- · 2020-02-10 08:26

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.

查看更多
劳资没心,怎么记你
4楼-- · 2020-02-10 08:27

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. 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.

查看更多
Viruses.
5楼-- · 2020-02-10 08:30

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;
}
查看更多
爷的心禁止访问
6楼-- · 2020-02-10 08:32

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.

查看更多
登录 后发表回答