Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy one map into another using std::copy?

Tags:

I would like to copy the content of one std::map into another. Can I use std::copy for that? Obviously, the following code won't work:

int main() {   typedef std::map<int,double> Map;   Map m1;   m1[3] = 0.3;   m1[5] = 0.5;   Map m2;   m2[1] = 0.1;   std::copy(m1.begin(), m1.end(), m2.begin());   return 0; } 

This won't work because copy will call operator* on m2.begin() to "dereference" it and assign a value (all values are of type std::pair<const int, double>). Then it will call operator++ to move to the next space in m2. Both of these operations don't work because of the const in const int and there is no space reserved for any new elements.

Is there any way to make it work with std::copy?

Thanks!

like image 916
Frank Avatar asked Apr 30 '10 23:04

Frank


People also ask

How do you copy a map?

If you just want to copy the map or are running Windows 7, press PrtScn to take a screenshot. If you have multiple screens open and don't want them all to appear in the shot, select the Google Maps screen and use Alt-PrtScn to shoot just that window. Your system places a copy of screenshots on your clipboard.

Can std::map have duplicates?

a map will not throw any compile/run time error while inserting value using duplicate key. but while inserting, using the duplicate key it will not insert a new value, it will return the same exiting value only. it will not overwrite.


2 Answers

You can use GMan's answer --- but the question is, why do you want to use std::copy? You should use the member function std::map<k, v>::insert instead.

m2.insert(m1.begin(), m1.end()); 
like image 194
Billy ONeal Avatar answered Sep 24 '22 15:09

Billy ONeal


You need a variant of an insert iterator:

std::copy(m1.begin(), m1.end(), std::inserter(m2, m2.end()) ); 

inserter is defined in <iterator>. It requires a place to insert into (hence the m2.end()), and returns an insert_iterator.

like image 32
GManNickG Avatar answered Sep 23 '22 15:09

GManNickG