c++ - 如何迭代这个 map ?

标签 c++ compiler-construction dictionary


我有一个函数,其中 const std::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 ========== 

最佳答案

看起来pDataPool是常量。所以你需要使用const_iterator:

std::map<std::string, Array2D<unsigned short>&>::const_iterator it = pDataPool->begin()

关于c++ - 如何迭代这个 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340250/

相关文章:

c++ - 在命名空间中使用指令和函数重载

c++ - allegro5 (C++) 中的另一幅图像

parsing - 为什么有些编译器更喜欢手工制作的解析器而不是解析器生成器?

c# - 如何根据 C# 中缺少的属性生成编译器错误?

c# - 为什么JIT订单会影响性能?

python - 如何通过嵌套键对嵌套字典进行排序

Java抽象类包含一个map变量,子类使用不同的实现初始化map

python - 在字典中使用整数类型键的字符串格式在 Python 2 中返回 KeyError,适用于字符串类型键

c++ - 使用 std::cin 可以将多长的字符串读入字符串对象?

c++ - 友元函数的作用域