C ++ STL Card - Conditional Insertion

I am looking for an effective way to do conditional insertion. Ideally, I need a template function that will work on any card. I want something like this:

std::map<int, std::string> MyMap; if(MyMap.ConditionalInsert(3, "Hello")) { // there was no element 3, one has been added with value "Hello" } else { // there was already an element 3 in the map, it unchanged } 

I cannot easily use operator[] , because there is no easy way to determine if it created an element or not. I can use count for the test, but then I need to do a map search twice if we do an insert. I think something with find would be better, but it always seems like it looks peppy and uncomfortable.

Is there a really good way to do this?

+4
source share
3 answers

What problem do you see:

 auto ret = MyMap.insert(std::make_pair(3, "Hello")); if( ret.second) { //the value is inserted } else { //no value is inserted } 

The return value indicates whether this value is present or not. If it is not there, the value will be inserted; otherwise, the value will not be inserted.

Taken from here :

... returns a pair with a member-pair: an iterator is first set, pointing either to a newly inserted element or to an element that already had the same value on the map. Pair :: the second element in the pair is true if a new element has been inserted or false if there is an element with the same value.

+5
source

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 
+5
source

The insert function already does what you want.

 std::pair<std::map<int, std::string>::iterator, bool> insertionResult = MyMap.insert(std::make_pair(3, "Hello")); if(insertionResult.second) { // there was no element 3, one has been added with value "Hello" } else { // there was already an element 3 in the map, it unchanged } 

The first element of the pair sets the location of the element with the key, old or new.

+1
source

Source: https://habr.com/ru/post/1386802/


All Articles