如何修改std::map容器中的键值
鉴于
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)
{
// ...
}
应用重新索引的好方法是什么?我必须删除旧条目并添加具有新密钥和旧值的新条目吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看来你最好构建一张新地图,然后再更换它。您将只有
n
次插入操作,而不是n
删除和n
插入操作。Looks like you are better off building a new map and swapping it afterward. You'll have only
n
insert operations instead ofn
deletions andn
insertions.是的,您必须删除旧条目并使用新密钥添加新条目。密钥不可修改。
如果您只修改一个或几个元素,则可以通过使用新元素的位置提示
map::insert
来有效地完成此操作。由于您的新键肯定位于旧键之后的某个位置,因此您可以使用指向旧元素的迭代器进行提示。但是,您必须注意不要重新评估新插入的键(例如,通过从头到前迭代),并且在修改整个映射的情况下,构建一个新映射会更有效。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.是的,你必须。当键在映射中时,它是 const。
Yes, you must. The key is const while it is in the map.
我认为你必须构建一张新地图。如果您在循环中删除并添加新键,则可能会破坏迭代旧键集的完整性,并且不会触及刚刚插入的键。 (除非你知道你的密钥是如何分配的并把你自己的逻辑放在那里。)
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.)
还有一种选择。如果此操作是您的集合的一个重要功能,并且性能很重要,那么您可以完全避免复制地图。您可以创建一个重载
operator[]
的类,以及其他访问器和修改器,并添加键值的当前移位。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.