将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>>
当然,你只需要将int转换为字符串。我建议是这样的:
string newKey(itoa(key));
(检查,工程第一:))
'itoa'是非标准的。试试'std :: to_string'。 – chris 2013-03-07 23:38:47
@chris yep!这听起来更好。 – 2013-03-07 23:43:53
恭敬地从@Ceasars删除答案the last time this was asked被盗......
- 创建
std::map<std::string, vector<int>>
- 迭代旧地图
- 将密钥更改为std :: string
- 插入到新的地图
步骤3可以与boost::lexical_cast
,std::to_string
来完成(在C++ 11),或非标准itoa
。
我用Itoa我得到这个错误的错误:itoa没有在这个范围内申报 – Angel 2013-03-08 00:01:00
然后我尝试使用std :: string = std :: to_string(m1-> first),我得到错误:to_string不是std的成员 – Angel 2013-03-08 00:04:27
我在步骤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);
});
要变换该怎么办钥匙? – inf 2013-03-07 23:34:39
这与你的其他问题恰恰相反。答案发表的作品几乎完全一样。 – chris 2013-03-07 23:36:48
有很好的提示[这个答案](http://*.com/questions/15281111) – 2013-03-07 23:37:42