2

Can we copy contents one one map to another map with different type of key? copy std::map<int, vector<int>> to std::map<std:string, vector<int>>

5
  • 1
    How do you want to transform the keys? Commented Mar 7, 2013 at 23:34
  • 1
    This is just the reverse of your other question. The answer posted works almost exactly the same. Commented Mar 7, 2013 at 23:36
  • There are good hints at this answer Commented Mar 7, 2013 at 23:37
  • Yes, but my previous question was deleted before i could finish reading it. Commented Mar 7, 2013 at 23:38
  • @Angel, Here: pastebin.com/gXuUVGgD Commented Mar 7, 2013 at 23:39

3 Answers 3

3

You can't copy them. While the maps are instantiated from the same class template, they're still unrelated types, much like struct Foo {}; and struct Bar {};

You can transform one to the other, though:

std::map<int, std::vector<int>> m1;
std::map<std::string, std::vector<int>> m2;

std::transform(m1.begin(), m1.end(), std::inserter(m2, m2.end()),
    [](const std::pair<int, std::vector<int>>& p)
    {
        return std::make_pair(std::to_string(p.first), p.second);
    });
Sign up to request clarification or add additional context in comments.

2 Comments

I get Error: to_string not a member of std
@Angel If you included <string> and the error is still there, it means your version of standard library doesn't have this function yet (it's relatively new to the C++ standard). Do some research on how to convert an int to string pre C++11.
1

Respectfully stolen from @Ceasars deleted answer the last time this was asked...

  1. Create an std::map<std::string, vector<int>>
  2. Iterate through the old map
  3. Change the key to be a std::string
  4. Insert to the new map

Step 3 can be done with boost::lexical_cast, std::to_string (in C++11), or the nonstandard itoa.

3 Comments

I used Itoa I get this error error: itoa was not declared in this scope
And then I tried using std::string = std::to_string(m1->first), I get Error: to_string not a member of std
I am getting error in step 4, std::string key = std::to_string(m1->first) , after this i m doing m2.insert(key, m1->second) But I get error saying no matching function for call to
0

Sure, you just need to convert the int to a string. I would suggest something like this:

string newKey(itoa(key));

(Check that that works first :) )

2 Comments

itoa is non-standard. Try std::to_string.
@chris yep! that sounds better.

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.