错误打印地图的元素值

时间:2012-12-16 07:07:59

标签: c++ map

map<char, int> counter;

//some code...

map<char, int>::iterator iter;

for (i = 0; i<26; i++) 
    {
    for (iter = counter[i].begin(); iter != counter[i].end(); iter++)  //error occurs
         {
         cout << (*iter).first << " - " << (*iter).second << endl;
         }

    }

我不确定此错误消息的含义: *错误:请求成员âbeginâ在âcounter.std:: map&lt; _Key,_Tp,_Compare,_ Alloc&gt; :: operator [] [与_Key = char,_Tp = int,_Compare = std :: less,_Alloc = std :: allocator&gt;,std :: map&lt; _Key,__Tp,_Compare,_Alloc&gt; :: mapped_type = int,std :: map&lt; _Key,_Tp,_Compare,_Alloc&gt; :: key_type = char]((*&amp;((std) :: map :: key_type)j)))â,非类* *类型âstd:: map :: mapped_type {aka int}â*

1 个答案:

答案 0 :(得分:1)

计数器是一个映射而不是一个map数组,一个for循环从begin()到end()就足够了,将你的for循环更改为下面的代码。

    map<char, int> counter;

   //some code...

    for (map<char, int>::iterator iter = counter.begin(); iter != counter[i].end(); ++iter)
    {
       cout << (*iter).first << " - " << (*iter).second << endl;
    }