开发者

Change the value in std::map from iterator

My application merges two std::map instances. If there are no duplicates, the merge completes without intervention. However, if a duplicate is detected, then the method asks whether the new value should be ignored or overwritten. (This query may be answered by a rule table, message box to the user, or some other logic ... it is just an instance of a class derived from a pure virtual class with a bool confirm() const method.)

If the insert fails, and they decide to overwrite the existing entry, I already have an iterator pointing to the correct item to update. Can I use this iterator to update the value directly, or do I have to call operator[] and take the hit of another lookup?

// typedef std::map<Foo, Foo, Compare> Dictionary;
// Dictionary this_dictionary, other_dictionary;
for (Dictionary::const_iterator i = other_dictionary.begin();
     i != other_dictionary.end();
  开发者_如何转开发   ++i) {
  std::pair<Dictionary::iterator,bool> ret = this_dictionary.insert(*i);
  if (!ret.second && confirmer.confirm()) {
    // ???
  }
}


You need to use Dictionary::iterator instead of Dictionary::const_iterator in the return from insert.

for (Dictionary::const_iterator i = other_dictionary.begin();
     i != other_dictionary.end();
     ++i) {
  // Use standard iterator here
  std::pair<Dictionary::iterator,bool> ret = this_dictionary.insert(*i);
  if (!ret.second && confirmer.confirm()) {
    ret.first->second = i->first; 
  }
}


You can, but you need to use iterator instead of const_iterator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜