如何解决如何迭代这张地图?
| 我有一个函数,其中conststd::map<std::string,Array2D<unsigned short>&>* pDataPool
是其输入参数之一。函数主体中有一个代码段,如下所示:
std::map<std::string,Array1D<unsigned short>*> DataBuffers;
if (pDataPool != NULL)
{
for (std::map<std::string,Array2D<unsigned short>&>::iterator it = pDataPool->begin();
it != pDataPool->end(); it++) // Error
{
std::string sKeyName = it->first;
DataBuffers[sKeyName] = new Array1D<unsigned short>(2048);
}
}
编译器输出:
1>e:\\program files\\microsoft visual studio 9.0\\vc\\include\\map(168) : error C2529: \'[]\' : reference to reference is illegal
1> f:\\tips\\tips\\fy2svsdataiohandler.cpp(77) : see reference to class template instantiation \'std::map<_Kty,_Ty>\' being compiled
1> with
1> [
1> _Kty=std::string,1> _Ty=Array2D<unsigned short> &
1> ]
1>f:\\tips\\tips\\fy2svsdataiohandler.cpp(77) : error C2440: \'initializing\' : cannot convert from \'std::_Tree<_Traits>::const_iterator to <br/>\'std::_Tree<_Traits>::iterator\'
1> with
1> [
1> _Traits=std::_Tmap_traits<std::string,Array2D<unsigned short> &,std::less<std::string>,std::allocator<std::pair<const <br/> std::string,Array2D<unsigned short> &>>,false>
1> ]
1> No constructor Could take the source type,or constructor overload resolution was ambiguous
1>Build log was saved at \"file://f:\\Tips\\Tips\\Debug\\BuildLog.htm\"
1>Tips - 2 error(s),0 warning(s)
========== Build: 0 succeeded,1 Failed,0 up-to-date,0 skipped ==========
解决方法
看起来a3ѭ是常数。因此,您需要使用
const_iterator
:
std::map<std::string,Array2D<unsigned short>&>::const_iterator it = pDataPool->begin()
, 看这里:为什么引用数组非法?
您应该使用指针而不是引用。指针还具有其他优点:明确表明数据将被更改。
, for (std::map<std::string,Array2D<unsigned short>&>::iterator it
应该读
for (std::map<std::string,Array2D<unsigned short>*>::iterator it
您不能将引用存储在标准容器中; (您可以使用std::ref
包裹它们,但这又是一个话题...)。
, 已经有一些答案,但让我总结一下。注意映射的类型(它是一个指针!它是1D还是2D?)-甚至更好的是,使用typedef来混淆自己:
typedef Array3D<unsigned short> Array; // decide on 1D,2D,3D,...!
typedef std::map<std::string,Array*> ArrayMap;
ArrayMap DataBuffers;
ArrayMap * pDataPool;
/* ... */
if (pDataPool != NULL)
{
for (ArrayMap::const_iterator it = pDataPool->begin(),end = pDataPool->end(); it != end; ++it)
{
const std::string & sKeyName = it->first;
DataBuffers[sKeyName] = new Array(2048); // terrible,use shared_ptr<Array>!
}
}
注重细节是关键。一些注意事项:
用原始指针作为映射类型是很糟糕的。如果该元素已经存在并且您仅用new
指针覆盖了该怎么办?内存泄漏!您应该认真考虑将地图设为std::map<std::string,std::tr1::shared_ptr<Array> >
。
如果您有很多条目,则字符串会导致键类型不正确。考虑改为std::tr1::unordered_map
。 (如果您使用的是C ++ 0x或MSVC10,请省略ѭ13。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。