In C++, how would I swap two elements of a map
?
The provided answers are correct but are using operator[]
twice for the same keys, which isn't free and could be avoided :
std::map<char, std::string> a;
Solution 1 :
std::string &item1 = a['a'];
std::string &item2 = a['b'];
std::swap(item1, item2);
Solution 2 :
const std::map<char, std::string>::iterator item1 = a.find('a');
const std::map<char, std::string>::iterator item2 = a.find('b');
if ((item1 != a.end()) && (item2 != a.end()))
std::swap(item1->second, item2->second);
Of course, the two solutions aren't equivalent (solution 2 only swaps values which are already in the map, solution 1 inserts without questioning and might end up swapping two default constructed strings).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With