The function insert of std::map would fail if the key equivalent to the one of an element already in the container.
when it happens, the new element is not inserted, and return an iterator to this existing element.

Demo:

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>

struct Node
{
    int id;
    char ch;
    Node() { id = -1; ch = -1; }
    Node(int _id, char _ch) { id = _id; ch = _ch; }
};

int main() {
    std::map<int, Node> container;
    container.insert( std::make_pair( 1, Node() ) );
    container.insert( std::make_pair( 2, Node(2, '2') ) );
    auto result = container.insert( std::make_pair( 1, Node( 1, '1' ) ) ); // return pair<iterator,bool> obj
    std::cout << result.first->second.id << " " << result.second << std::endl; // -1 0 //  insert failed.

    for( auto itr: container )
    {
        std::cout << itr.first << " " << itr.second.id << " " << itr.second.ch << std::endl;
    }
    /*
     * 1 -1 
     * 2 2 2
     * */

    return 0;
}

The update can be done successfully if we use operator [] for the above program.

    std::map<int, Node> container;
    container[1] = Node();
    container[2] = Node(2, '2');
    container[1] = Node( 1, '1' );

    for( auto itr: container )
    {
        std::cout << itr.first << " " << itr.second.id << " " << itr.second.ch << std::endl;
    }
    /*
    * 1 1 1
    * 2 2 2
     * */

Reference introduction: https://cplusplus.com/reference/map/map/insert/

Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x