How can I copy one map into another using std::copy?
Solution 1
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());
Solution 2
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
.
Related videos on Youtube
Frank
Updated on July 09, 2022Comments
-
Frank almost 2 years
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 calloperator*
onm2.begin()
to "dereference" it and assign a value (all values are of typestd::pair<const int, double>
). Then it will calloperator++
to move to the next space inm2
. Both of these operations don't work because of theconst
inconst int
and there is no space reserved for any new elements.Is there any way to make it work with
std::copy
?Thanks!
-
Billy ONeal about 14 years+1 for correct answer, but one should prefer member functions to algorithm calls.
-
Stephen about 14 yearsWell, if you're gonna avoid using std::copy, why not just use the copy c'tor? m2 = m1. edit: Ah, he wants the union of values.
-
Billy ONeal about 14 years@Stephen: Because using
insert
preserves the existing contents insidem2
. Using the copy assignment operator destroys the existing contents insidem2
. -
Dean Burge about 14 years+1 @GMan, +1 @Billy, you guys both got it right. The OP should do what Billy suggests, but GMan in fact answered the question. So, with your powers combined ...
-
GManNickG about 14 years@WilhelmTell: I AM CAPTAIN PLANET!
-
cheshirekow over 10 years@Billy: Your answer is clearly the correct answer for the OP, but the answer to why would be "so I can use copy_if", and filter one map during the copy to another.
-
Billy ONeal over 10 years@Cheshire
copy_if
!=copy
. -
kalaxy almost 10 yearsThis version works nicely when using the copy_if variant of c++11.
-
Olshansk almost 4 yearsStupid question, but why not just do
Map m2 = m1;
?