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>>
-
1How do you want to transform the keys?Stephan Dollberg– Stephan Dollberg2013-03-07 23:34:39 +00:00Commented Mar 7, 2013 at 23:34
-
1This is just the reverse of your other question. The answer posted works almost exactly the same.Qaz– Qaz2013-03-07 23:36:48 +00:00Commented Mar 7, 2013 at 23:36
-
There are good hints at this answerDrew Dormann– Drew Dormann2013-03-07 23:37:42 +00:00Commented Mar 7, 2013 at 23:37
-
Yes, but my previous question was deleted before i could finish reading it.Angel– Angel2013-03-07 23:38:33 +00:00Commented Mar 7, 2013 at 23:38
-
@Angel, Here: pastebin.com/gXuUVGgDQaz– Qaz2013-03-07 23:39:57 +00:00Commented Mar 7, 2013 at 23:39
Add a comment
|
3 Answers
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);
});
2 Comments
Angel
I get Error: to_string not a member of std
jrok
@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.Respectfully stolen from @Ceasars deleted answer the last time this was asked...
- Create an
std::map<std::string, vector<int>> - Iterate through the old map
- Change the key to be a std::string
- 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
Angel
I used Itoa I get this error error: itoa was not declared in this scope
Angel
And then I tried using std::string = std::to_string(m1->first), I get Error: to_string not a member of std
Angel
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 toSure, 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
Qaz
itoa is non-standard. Try std::to_string.Fantastic Mr Fox
@chris yep! that sounds better.