Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a std::map vs move all the elements of a std::map

std::map<int, Obj> mp;
// insert elements into mp

// case 1
std::map<int, Obj> mp2;
mp2 = std::move(mp);

// case 2
std::map<int, Obj> mp3;
std::move(std::begin(mp), std::end(mp), std::inserter(mp3, std::end(mp3));

I am confused by the two cases. Are they exactly the same?

like image 485
Yves Avatar asked Dec 31 '22 12:12

Yves


1 Answers

Are they exactly the same?

No, They are not!

The first one invokes the move constructor of the std::map4 and the move operation will be done at class/ data structure level.

[...]

  1. Move constructor. After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in container.requirements.general, and a more direct guarantee is under consideration via LWG 2321

Complexity

4) Constant. If alloc is given and alloc != other.get_allocator(), then linear.


The second std::move is from <algorithm> header, which does element wise(i.e. key value pairs) movement to the other map.

  1. Moves the elements in the range [first, last), to another range beginning at d_first, starting from first and proceeding to last - 1. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.

Complexity

Exactly last - first move assignments.

like image 72
JeJo Avatar answered Jan 05 '23 18:01

JeJo