Advertisement
Rochet2

testing insert or replace

Dec 5th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <unordered_map>
  4. #include <string>
  5.  
  6. struct MyObj
  7. {
  8.     MyObj(int i) : i(i) { std::cout << "constructed " << i << std::endl; }
  9.     MyObj(const MyObj& other) : i(other.i) { std::cout << "copyconstructed " << i << std::endl; }
  10.     MyObj(MyObj&& other) : i(std::forward<int>(other.i)) { std::cout << "moved " << i << std::endl; }
  11.     int i;
  12.    
  13.     MyObj& operator=(const MyObj& other)
  14.     {
  15.         this->i = other.i;
  16.         std::cout << "copied1 " << i << std::endl;
  17.         return *this;
  18.     }
  19.    
  20.     MyObj& operator=(MyObj&& other)
  21.     {
  22.         this->i = other.i;
  23.         std::cout << "copied2 " << i << std::endl;
  24.         return *this;
  25.     }
  26. };
  27.  
  28. struct KeyHash {
  29.  std::size_t operator()(const MyObj& k) const
  30.  {
  31.      return std::hash<int>()(k.i);
  32.  }
  33. };
  34.  
  35. struct KeyEqual {
  36.  bool operator()(const MyObj& lhs, const MyObj& rhs) const
  37.  {
  38.     return lhs.i == rhs.i;
  39.  }
  40. };
  41.  
  42. void InsertOrReplace(std::unordered_map<MyObj, MyObj, KeyHash, KeyEqual>& mymap, MyObj&& key, const MyObj& value)
  43. {
  44.     // try insert new element to mymap
  45.     auto result = mymap.emplace(std::make_pair(std::forward<MyObj&&>(key), value));
  46.     if (!result.second)
  47.         result.first->second = value;
  48. }
  49.  
  50. int main()
  51. {
  52.     std::unordered_map<MyObj, MyObj, KeyHash, KeyEqual> mymap;
  53.     InsertOrReplace(mymap, MyObj(1), MyObj(2));
  54.     std::cout << std::endl;
  55.     InsertOrReplace(mymap, MyObj(1), MyObj(2));
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement