How to replace map elements

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

+3
source share
5 answers

What do you mean swap on the map? A normal simple map of vanilla does not have any special order, so speaking of an exchange it makes no sense with respect to order.

If you are looking for a C ++ map implementation that keeps order, in which case ordering becomes meaningful, look here

If you want to change the value associated with one key with the value associated with the second key, simply do

  map<char,string> mymap;

  mymap['a']="firstValue";
  mymap['b']="SecondValue";
  /*now let swap*/
  string tmpString = mymap['a'];
  mymap['a']=mymap['b'];
  mymap['b']= tmpString
+1
source

, operator[] , :

std::map<char, std::string> a;

1:

std::string &item1 = a['a'];
std::string &item2 = a['b'];
std::swap(item1, item2);

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

, ( 2 , , 1 ).

+5

, std::swap() - .

+3

.

template<class Key, class Value>
void swap_map_elements(std::map<Key, Value>& map, const Key& key1, const Key& key2)
{
    auto it1 = map.find(key1);
    auto it2 = map.find(key2);
    auto end = map.end();

    if(it1 != end && it2 != end) {
        std::swap(it1->second, it2->second);
    }
    else if(it1 != end) {
        map.emplace(std::make_pair(key2, std::move(it1->second)));
        map.erase(key1);
    }
    else if(it2 != end) {
        map.emplace(std::make_pair(key1, std::move(it2->second)));
        map.erase(key2);
    }
}

:

auto M = std::map<int, std::string>();
M.emplace(std::make_pair(1, "one"));
M.emplace(std::make_pair(2, "two"));

swap_map_elements(M, 1, 2); // 1: "two", 2: "one"
swap_map_elements(M, 1, 4); // 2: "one", 4: "two"
swap_map_elements(M, 5, 2); // 4: "two", 5: "one"
swap_map_elements(M, 8, 9); // 4: "two", 5: "one"
+1

?

const T tmp = map["a"];
map["a"] = map["b"];
map["b"] = tmp;
0

Source: https://habr.com/ru/post/1775951/


All Articles