0
我有一个问题,从一个名为“files”的指针向量创建一个std :: map,每个指向一个具有三个成员变量的对象,其中之一是“int size”。地图的关键是大小,值将是具有相同“大小”的对象的数量。不要浪费你的时间在第二个,这是我的程序中的下一步,我已经找到了,我想。对于映射的初始化,我使用std :: accumulate,因为它返回一个值。我使用指针std :: tr1 :: shared_ptr和谓词函数的lambda表达式。我有问题,编译:使用std :: accumulate生成地图的C++ <int,int>
map<int,int>* sizes = new map<int,int>();
sizes = accumulate(files.begin(), files.end(),sizes,
[&sizes](map<int,int> acc, shared_ptr<CFileType>& obj)
{
return sizes->insert(pair<int,int>(obj->getSize(),0));
});
error C2664: 'std::pair<_Ty1,_Ty2> `anonymous-namespace'::<lambda4>::operator()(std::map<_Kty,_Ty>,std::tr1::shared_ptr<CFileType> &) const' : cannot convert parameter 1 from 'std::map<_Kty,_Ty> ' to 'std::map<_Kty,_Ty>'
我不是很知道该怎么传递给lambda函数,我有一双尝试,但它didn`t工作。另外,我必须注意,这个映射返回到另一个函数,所以它必须是一个指针。任何帮助,将不胜感激。
问题解决了,这里是解决方案:
map<int,int>* sizes = accumulate(files.begin(), files.end(), new map<int,int>(),
[](map<int,int>* acc, shared_ptr<CFileType>& obj)->map<int,int>*
{
acc->insert(pair<int,int>(obj->getSize(),0));
return acc;
});
哪个是我有的两种“地图”?感谢您找到一个不需要的算法,我确实想使用“acc”,但在lambda函数中使用了“sizes”。 – Goshutu 2012-03-24 15:36:34
虽然我知道其中一个“地图”的类型,但我没有看到其他的类型。但错误信息“'不能将参数1从'std :: map <_Kty,_Ty>'转换为'std :: map <_Kty,_Ty>''”的意思就是,即使它没有告诉你'_Kty'和'_Ty'的类型在每个地图中。当你实际使用lambda时,你必须看到你传递给lambda的第一个参数,并确定类型与'std :: map'不同。 –
2012-03-24 16:36:06
它现在可以工作,我没有意识到map.insert()不会返回地图,但它会插入它。该代码现在可用。 – Goshutu 2012-03-24 16:51:24