Monday, October 23, 2017

C++17: try_emplace

C++17 added the try_emplace() function to std:: map. The try_emplace() function stores a value if the key is not already there. Here is an example:

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

int main()
{
  std::map<std::string, std::string> myMap;
  myMap.try_emplace("a", "apple"     );
  myMap.try_emplace("b", "bannana"   );
  myMap.try_emplace("c", "cherry"    );
  myMap.try_emplace("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 : cherry;
Reference: https://en.wikipedia.org/wiki/C%2B%2B17

No comments:

Post a Comment