Do not overwrite previous values, what to use?
std::map<T1,T2>::insert already performs this check for you, if there is already an entry with the specified key, the insert will be interrupted.
std::map<int, std::string> m; m.insert (std::make_pair (3, "hello world")); m.insert (std::make_pair (3, "world hello")); std::cerr << m[3] << std::endl;
output:
hello world
Has a new value been inserted?
std::map<T1,T2>::insert returns a std::pair<std::map<T1,T2>::iterator, bool> , the second value ( pair.second ) will act as a flag indicating whether whether a key / value pair is inserted.
if ret.second == true: value was inserted if ret.second == false: the key has already been set
Fragment example:
std::cerr << m.insert (std::make_pair (1,1)).second << std::endl; std::cerr << m.insert (std::make_pair (1,2)).second << std::endl;
Output
1 0
source share