3

I would like to do the following but it seems it is not possible. I am no expert on STL.

typedef std::map<int,int> CMap;

CMap m1;
m1[0] = 10;
m1[1] = 11;
m1[2] = 12;

CMap m2;
m2[20] = 30;
m2[21] = 31;
m2[22] = 32;

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

Is there a way to do this using an algorithm (C++98)? Could it be done with transform() or replace()? If yes, how?

Thanks!

6
  • Duplicate? stackoverflow.com/questions/5103532/… Commented Apr 29, 2015 at 6:42
  • Maybe you could use std::inserter for the last argument? Commented Apr 29, 2015 at 6:45
  • @Morb: Thanks. insert() is of course possible. I wondered if it is also possible doing likewise with an algorithm. Commented Apr 29, 2015 at 6:49
  • @Joachim: Thanks. That is one way that I did not consider. Actually I did not specify what I want to do properly. I would like to have m2 overwritten by m1. Would that also be possible? Commented Apr 29, 2015 at 6:59
  • Better clarify that in the question itself. Commented Apr 29, 2015 at 7:13

1 Answer 1

4

You can do this:

m2 = m1;

Or even this if you like:

m2.swap(m1);

And there is this too:

std::copy(m1.begin(), m1.end(), std::inserter(m2, m2.end()));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. The first two overwrite which is good but the third will just append as I understand. Is there a way to overwrite using copy()?
@Lorenz You could overwrite using std::copy() if you created your own iterator as std::insert_iterator will only insert if there is not a value already present. TBH you might as well just write a loop as any method is going to at least require you to write a functor. If you have C++11 a simple range based for loop would do it: for(auto&& p: m1) m2[p.first] = p.second;
Thanks for the answer. Did not think of the possibility to write a specific iterator. Now clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.