muXXmit2X
muXXmit2X

Reputation: 2765

Inserting into a std::map and manipulating the obtained iterator to the inserted element

I know that, if I insert a value into a std::map I can obtain an iterator referring to the inserted element (or the element which was previously there) by checking inserts return value like so:

std::map<int, char> m;
auto ret = m.insert(std::make_pair(1, 'A'));
if (ret.second)
    std::cout << "it worked" << std::endl;
// ... now iterations over the map starting at ret.first

However, I was wondering whether it is legal to manipulate the obtained iterator afterwards, e.g. assign the desired value in the case of a failure.

std::map<int, char> m;
auto ret = m.insert(std::make_pair(1, 'A'));
if (!ret.second)
    ret.first->second = 'A'; // assign the value in case it went wrong

I noticed that this seems to work, but I am not sure whether this is the desired behaviour since everything I found in case of an failed insertion was to use the operator[] instead. However this would not be a solution for me, because I need the iterator returned by insert afterwards and I can't use insert and the operator[] because of performance reasons.

Long story short: Is it valid to manipulate the data referenced by an iterator returned from std::maps insert()?

Upvotes: 1

Views: 76

Answers (1)

NathanOliver
NathanOliver

Reputation: 181057

Long story short: Is is valid to manipulate the data referenced by an iterator returned from std::maps insert()?

Yes, this is just fine. You cannot modify the key as that is const but you can modify the value the key is mapped to as much as you want.

Upvotes: 3

Related Questions