Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c++ - Can I move-assign a std::map's contents into another std::map?

Is it possible to insert the contents of a temporary std::map temp into another std::map m by using move semantics, such that the values from the temporary are not copied and are reused?

Let's say one has:

std::map<int, Data> temp;
std::map<int, Data> m;

One way of copying values from temp into m is:

m.insert(temp.begin(),temp.end());

How can I move the temp elements into m, instead of copying?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

HINT: Read the update first!

The current C++11 standard and the C++14 draft do not provide a member function to enable this feature. As lavr suggested you can still write

m.insert(make_move_iterator(begin(temp)),
         make_move_iterator(end  (temp)));

which will move the values from the source container into the destination container. However, neither the container nodes nor the keys will be moved. This requires memory allocations (at least for the creation of the new nodes in the destination map). The number of elements in the source container will remain the same. The reason behind the copying is simple: The value type of std::map is std::pair<const Key,T>. And moving from a const Key is essentially copying the key (unless someone overloaded the Key constructor which takes a const Key &&, for which I cannot think of an adequate reason).

If you need to move data from one container to another you may consider using std::list instead of std::map. It has a member function splice which moves the elements from one list to another in constant time.

UPDATE:

Since C++17 there is the function std::map::merge() which basically puts all the elements of one std::map into another std::map without moving or copying the actual elements, but by repointing internal pointers only. It is very similar to std::list::splice() which exists since C++98.

So you may write

m.merge( temp );

to accomplish your goal. This is more efficient than copying or moving all the elements from one container to the other.

But beware! Conflicting keys won't be resolved: For coinciding keys nothing will be done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...