Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap map elements

Tags:

c++

map

stl

swap

In C++, how would I swap two elements of a map?

like image 430
wrongusername Avatar asked Dec 10 '22 12:12

wrongusername


1 Answers

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).

like image 194
icecrime Avatar answered Dec 15 '22 00:12

icecrime