将std :: map >复制到std :: map >

问题描述:

我们可以将内容一个地图复制到另一个具有不同类型的地图的地图吗? copy std::map<int, vector<int>> to std::map<std:string, vector<int>>将std :: map <int,vector <int>>复制到std :: map <std:string,vector <int>>

+1

要变换该怎么办钥匙? – inf 2013-03-07 23:34:39

+1

这与你的其他问题恰恰相反。答案发表的作品几乎完全一样。 – chris 2013-03-07 23:36:48

+0

有很好的提示[这个答案](http://*.com/questions/15281111) – 2013-03-07 23:37:42

当然,你只需要将int转换为字符串。我建议是这样的:

string newKey(itoa(key)); 

(检查,工程第一:))

+1

'itoa'是非标准的。试试'std :: to_string'。 – chris 2013-03-07 23:38:47

+0

@chris yep!这听起来更好。 – 2013-03-07 23:43:53

恭敬地从@Ceasars删除答案the last time this was asked被盗......

  1. 创建std::map<std::string, vector<int>>
  2. 迭代旧地图
  3. 将密钥更改为std :: string
  4. 插入到新的地图

步骤3可以与boost::lexical_caststd::to_string来完成(在C++ 11),或非标准itoa

+0

我用Itoa我得到这个错误的错误:itoa没有在这个范围内申报 – Angel 2013-03-08 00:01:00

+0

然后我尝试使用std :: string = std :: to_string(m1-> first),我得到错误:to_string不是std的成员 – Angel 2013-03-08 00:04:27

+0

我在步骤4中得到错误,'std :: string key = std :: to_string(m1-> first),在这个im之后做m2.insert(key,m1-> second)'但是我得到错误,说没有匹配的函数致电 – Angel 2013-03-12 22:14:55

你不能复制它们。虽然地图是同一类模板实例化,他们仍然不相关的类型,就像struct Foo {};struct Bar {};

您可以transform一个到另一个,虽然:

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); 
    }); 
+0

我收到错误:to_string不是std的成员 – Angel 2013-03-08 00:12:25

+0

@Angel如果你包含了''并且错误仍然存​​在,这意味着你的标准库的版本还没有这个功能呢(它对于C++标准)。做一些关于如何将一个int转换为字符串pre C++ 11的研究。 – jrok 2013-03-08 00:15:11