0

I'm using the std::map to save some stuff, the key is Guid*.

typedef boost::tuple<c_ptr, handler_ptr> ctuple;
typedef std::map<GUID *, ctuple> c_map;

My question is: Do I have a way to change the key of an item in the std::map? OTHER THAN copy the existing data to a new item that have the new key and remove the prev/old item (with the old key)

Thanks

Joseph
  • 1,716
  • 3
  • 24
  • 42
  • See also [How to modify key values in std::map container](http://stackoverflow.com/q/3884572/96780). – Daniel Daranas Sep 02 '14 at 09:35
  • 1
    Other than copy? *Move* the data to the new item :-) – Kerrek SB Sep 02 '14 at 09:37
  • Assuming the map is internally implemented with a balanced binary tree, just "changing" the key data would destroy the purpose and the order of the tree. The operations you listed are necessary to create a new item and delete / rebalance the tree. – Marco A. Sep 02 '14 at 09:43

1 Answers1

4

Do I have a way to change the key of an item in the std::map?

No.

This is why value_type of std::map<Key, Value> is std::pair<Key const, Value> (notice const applied to Key).

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • So the only way would be: ctuple tmp = c_map[oldKey]; c_map[NewKey]= tmp; c_map.erase[oldKey]; – Joseph Sep 02 '14 at 10:26
  • 1
    @Joseph Yep, something like that. In C++11 you can use `std::move` to move the value instead of copying it if it is relatively expensive to copy. – Maxim Egorushkin Sep 02 '14 at 10:39
  • thanks, I afraid that the std::move here not help. move from one map to other yes, but move the data between value in same map, i don't see it would be better to use move. – Joseph Sep 02 '14 at 11:32