Why C++ map.insert() doesn't overwrite

前端 未结 5 1376
误落风尘
误落风尘 2021-01-17 20:25

In the code below:

#include 
#include 
#include 

using namespace std;

int main(){
  pair p1(1,1);
         


        
相关标签:
5条回答
  • 2021-01-17 20:57

    Putting together the other answers, if you want to avoid the assumption of being default constructable you get insert-with-overwrite code that looks like this:

    auto itAndWasInserted = m.insert(p1);
    if (!itAndWasInserted.second) {
        *(itAndWasInserted.first) = p1;
    }
    

    If you want to avoid copy construction, but also want to avoid a second seek (for re-insertion), you end up with this monster:

    auto itAndWasInserted = m.insert(p1);
    auto it = itAndWasInserted.first;
    if (!itAndWasInserted.second) {
        auto afterIt = m.erase(it);
        auto newItAndWasInserted = m.insert(afterIt, p1);  // Hint form of insert
        it = newItAndWasInserted.first;
    }
    

    At the end of the code block, it is an iterator pointing at the just-inserted element.

    Realistically, in most cases you probably just want to use yizzlez's suggestion of operator[], but I thought it would be good to note the theoretically best answer.

    0 讨论(0)
  • 2021-01-17 20:58

    map.insert() only inserts if the container doesn't already contain an element with an equivalent key.

    You should use operator[] instead:

     m[p2.first] = p2.second;
    
    0 讨论(0)
  • 2021-01-17 21:02

    It doesn't overwrite. However if you check the return value, there is a std::pair<iterator, bool>. If bool is true, then it was inserted. If the bool is false, then it was not inserted because of a collision. At that point, you can then overwrite the data yourself by writing to the iterator.

    0 讨论(0)
  • 2021-01-17 21:02

    This is supposed to happen. map.insert() will only insert elements into the container if it doesn't already contain any elements, so this will ignore the later value elements assigned to it.

    0 讨论(0)
  • In the std::map::insert reference it is said that:

    Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.

    0 讨论(0)
提交回复
热议问题