Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- #include <unordered_map>
- #include <string>
- struct MyObj
- {
- MyObj(int i) : i(i) { std::cout << "constructed " << i << std::endl; }
- MyObj(const MyObj& other) : i(other.i) { std::cout << "copyconstructed " << i << std::endl; }
- MyObj(MyObj&& other) : i(std::forward<int>(other.i)) { std::cout << "moved " << i << std::endl; }
- int i;
- MyObj& operator=(const MyObj& other)
- {
- this->i = other.i;
- std::cout << "copied1 " << i << std::endl;
- return *this;
- }
- MyObj& operator=(MyObj&& other)
- {
- this->i = other.i;
- std::cout << "copied2 " << i << std::endl;
- return *this;
- }
- };
- struct KeyHash {
- std::size_t operator()(const MyObj& k) const
- {
- return std::hash<int>()(k.i);
- }
- };
- struct KeyEqual {
- bool operator()(const MyObj& lhs, const MyObj& rhs) const
- {
- return lhs.i == rhs.i;
- }
- };
- void InsertOrReplace(std::unordered_map<MyObj, MyObj, KeyHash, KeyEqual>& mymap, MyObj&& key, const MyObj& value)
- {
- // try insert new element to mymap
- auto result = mymap.emplace(std::make_pair(std::forward<MyObj&&>(key), value));
- if (!result.second)
- result.first->second = value;
- }
- int main()
- {
- std::unordered_map<MyObj, MyObj, KeyHash, KeyEqual> mymap;
- InsertOrReplace(mymap, MyObj(1), MyObj(2));
- std::cout << std::endl;
- InsertOrReplace(mymap, MyObj(1), MyObj(2));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement