Comparing the size of the map before insertion and after insertion to know if an element was inserted is slow (map::size is slow with Debian 8: browsing complete map)
It is possible to know whether a pair was inserted or found in a map after insertion with hint without recalculating size, using hint insertion method.
Insert with hint method another pair of the same first, and of a second that you are sure is not in the map ( like -1 for a map of positive second int). If the iterator returned has this impossible value, it has been newly inserted, if not it was found in the map. The iterator returned may then be changed.
Example : to insert pairs p (2,4) and p (6, 5) in the map<int, int> m ((0, 1), (2, 3), (4, 5)).
int main (int argc, char* argv []) {
std::pair<int, int> tmp [3] = {
std::pair<int, int> (0, 1),
std::pair<int, int> (2, 3),
std::pair<int, int> (4, 5)
};
std::map<int, int> m ((std::pair<int, int>*) tmp, (std::pair<int, int>*) &tmp [3]);
std::cout << "initial map == ";
std::for_each (m.begin (), m.end (), [] (const std::pair<int, int>& p) {
std::cout << p.first << "->" << p.second << " ";
});
std::cout << std::endl;
std::cout << std::endl;
{
//insertion of a pair of first already in map
std::cout << "insertion of pair 1 == std::pair<int, int> (2, 4) from second iterator" << std::endl;
std::map<int, int>::iterator ihint (m.begin ()), k (ihint); ++ihint;
std::pair<int, int> pfoo (2, -1);
k = m.insert (ihint, pfoo);
if (k->second == -1) {
std::cout << "\tthe pair was inserted" << std::endl;
k->second = 4;
}
else {
std::cout << "\ta pair with such a first was in the map" << std::endl;
}
}
std::cout << "m after insertion of pair 1 == ";
std::for_each (m.begin (), m.end (), [] (const std::pair<int, int>& p) {
std::cout << p.first << "->" << p.second << " ";
});
std::cout << std::endl;
std::cout << std::endl;
{
//insertion of a pair of first not in map
std::cout << "insertion of pair 2 == std::pair<int, int> (6, 5) from third iterator" << std::endl;
std::map<int, int>::iterator ihint (m.begin ()), k (ihint); ++ihint; ++ihint;
std::pair<int, int> pfoo (6, -1);
k = m.insert (ihint, pfoo);
if (k->second == -1) {
std::cout << "\tthe pair was inserted" << std::endl;
k->second = 5;
}
else {
std::cout << "\ta pair with such a first in the map" << std::endl;
}
}
std::cout << "m after insertion of pair 2 == ";
std::for_each (m.begin (), m.end (), [] (const std::pair<int, int>& p) {
std::cout << p.first << "->" << p.second << " ";
});
std::cout << std::endl;
}
outputs :
initial map == 0->1 2->3 4->5
insertion of pair 1 == std::pair<int, int> (2, 4) from second iterator
a pair with such a first was in the map
m after insertion of pair 1 == 0->1 2->3 4->5
insertion of pair 2 == std::pair<int, int> (6, 5) from third iterator
the pair was inserted
m after insertion of pair 2 == 0->1 2->3 4->5 6->5