Reputation: 199
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>>
Upvotes: 2
Views: 584
Reputation: 55395
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);
});
Upvotes: 3
Reputation: 63775
Respectfully stolen from @Ceasars deleted answer the last time this was asked...
std::map<std::string, vector<int>>
Step 3 can be done with boost::lexical_cast
, std::to_string
(in C++11), or the nonstandard itoa
.
Upvotes: 1
Reputation: 33864
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 :) )
Upvotes: 0