sa2304

Test std::map insert() vs emplace()

Nov 5th, 2020
1,918
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3.  
  4. using namespace std;
  5.  
  6. void PrintInsertResult(const pair<map<int, string>::iterator, bool> & result) {
  7.     auto [iter, inserted] = result;
  8.             auto [key, value] = (*iter);
  9.     if (inserted) {
  10.         cout << "Successfully inserted (" << key << ", " << value
  11.              << ") into map" << endl;
  12.     } else {
  13.         cout << "Value was not inserted, existing value found: ("
  14.              << key << ", " << value << ")" << endl;
  15.     }
  16. }
  17.  
  18. //------------------------------------------------------------------------------
  19. int main()
  20. {
  21.     map<int, string> numbers;
  22.  
  23.     cout << "insert(1, one)" << endl;
  24.     pair<map<int, string>::iterator, bool> first_inserted =
  25.             numbers.insert({1, "one"});
  26.     PrintInsertResult(first_inserted);
  27.  
  28.     cout << "insert(1, uno)" << endl;
  29.     auto duplicate_first_inserted = numbers.insert({1, "uno"});
  30.     PrintInsertResult(duplicate_first_inserted);
  31.  
  32.     cout << "emplace(1, uno)" << endl;
  33.     auto duplicate_first_emplaced = numbers.emplace(1, "uno");
  34.     PrintInsertResult(duplicate_first_emplaced);
  35.  
  36.     return 0;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment