Return type of std::map::insert

At the time I try to understand the behavior of the std::map facilities.
Especially I want to know of what type the map::insert return type is. I know that for such things the 'auto' type will be the better choice, and I usually use tat as much as possible. But the 'auto' makes it hard to understand what's really going on.

So I would be glad if someone would fix my code :-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<char,int> my_map;
    auto insert_ret_1 = my_map.insert(std::make_pair('a', 123));
    
    
    // Here I want to kow how the synax for the correct return type is.
    std::pair<std::pair<std::map<char,int>::iterator, bool> insert_ret_2 = my_map.insert(std::make_pair('a', 345));
    
    std::cout << "insert_ret_2.second == " << (insert_ret_2.second?"true":"false") << '\n';
    
    std::cout << insert_ret_2.first->first << '\n';
    std::cout << insert_ret_2.first->second << '\n';
}


*edit:
I found by trying at the concerned line that the correct type would be
std::pair<std::map<char,int>::iterator, bool>
Last edited on
std::map only stores one value per key so if the map already has a value for the key that you tried to insert (in this case 'a') the insertion will be rejected and the old value will remain in the map.

The insert function returns a pair of two values.

The second value tells you whether the insertion was successful or not.

The first value is an iterator to the newly inserted element, or to the element that prevented the insertion from taking place.
Using std::map is somewhat 'complicated' to handle to me because I needed it rarely. I struggled at first time with the fact that its iterator points not to the value element but rather to the key/value pair.
If you don't care if the key already exist or just want to overwrite or insert a new element you can just access the value using the subscript operator and assign to it.

 
my_map['a'] = 345;
Topic archived. No new replies allowed.