Angel
Angel

Reputation: 199

copy std::map<int, vector<int>> to std::map<std:string, vector<int>>

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

Answers (3)

jrok
jrok

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

Drew Dormann
Drew Dormann

Reputation: 63775

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.

Upvotes: 1

Fantastic Mr Fox
Fantastic Mr Fox

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

Related Questions