Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Swap Map Elements without Moving?

If I have two map<string, int>s how can I swap an element from each map?

For example:

map<string, int> ps{ { "triangle", 0 }, { "cross", 1 }, { "square", 2 }, { "circle", 3 } };
map<string, int> xbox{ { "y", 0 }, { "a", 1 }, { "b", 2 }, { "x", 3 } };

swap(move(ps["cross"]), move(xbox["x"]));

The swap statement is clearly wrong, but that explains what I want to do. After the swap statement I'd like ps to contain:

  • { "triangle", 0 }
  • { "x", 3 }
  • { "square", 2 }
  • { "circle", 3 }

And xbox to contain:

  • { "y", 0 }
  • { "a", 1 }
  • { "b", 2 }
  • { "cross", 1 }

I expect there is a good way to do this with C++11's move syntax, but if possible I'd like an answer that also describes how to accomplish this on C++03.

like image 404
Jonathan Mee Avatar asked Apr 13 '15 12:04

Jonathan Mee


1 Answers

map is implemented as an ordered tree.

You cannot simply replace a key with a new key as it might have to be placed on a different location in the tree. Consequently, you cannot swap.

Delete an re-insert the k-v pairs manually.

(As a sidenote: you haven't even told us what happens with the values...)

like image 172
Karoly Horvath Avatar answered Oct 15 '22 01:10

Karoly Horvath