Monday, October 23, 2017

C++17: insert_or_assign

C++17 added the insert_or_assign() function to the map and unordered_map containers. The function inserts an element or assigns an element if the key already exists. Here is an example:

#include <iostream>
#include <map>
#include <string>

int main()
{
  std::map<std::string, std::string> myMap;
  myMap.insert_or_assign("a", "apple"     );
  myMap.insert_or_assign("b", "bannana"   );
  myMap.insert_or_assign("c", "cherry"    );
  myMap.insert_or_assign("c", "clementine");

  for (const auto &pair : myMap)
  {
    std::cout << pair.first << " : " << pair.second << "; ";
  }
  std::cout << std::endl;
  return 0;
}
// Output: a : apple; b : bannana; c : clementine;
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/container/map/insert_or_assign

No comments:

Post a Comment