读书人

地图遍历的有关问题

发布时间: 2012-10-17 10:25:47 作者: rapoo

map遍历的问题
如题,我设置断点,map容器没问题,怎么遍历就是不出来。麻烦各大大看看那~~~


#include<iostream>
#include<map>
#include<string>


using namespace std ;

int main(){
map<string ,int> word_count ;
map<string ,int> ::iterator it = word_count.begin();

string word ;
int i = 0;

while (cin>>word && i < 5 )
{
++ word_count[word] ;
++ i ;
}


while (it != word_count.end()) //这个语句是错误的,不知道怎么遍历map容器呢。。。
{
cout<<it->second<<endl ;
it ++ ;


}


system("PAUSE") ;
return 0 ;


}


[解决办法]

C/C++ code
    for (map<string, int>::const_iterator iter = word_count.begin();        iter != word_count.end();        ++iter)    {        cout << iter->second << endl;    }
[解决办法]
C/C++ code
#include<iostream>#include<map>#include<string>using namespace std ;int main(){    map<string , int> word_count ;    map<string , int> ::iterator it = word_count.begin();    string word ;    int i = 0;    // 因为每次插入map 都会重新排序,所以it并不一定指向原来的 word_count.begin()    while (cin >> word && i < 5) {        ++ word_count[word] ;        ++ i ;    }    it = word_count.begin();   // 所以要把 it 再次指向 word_count.begin()    while (it != word_count.end()) {        cout << it->first << " : " << it->second << endl ;        it ++ ;    }    return 0 ;} 

读书人网 >C++

热点推荐