读书人

g关于map容器的count函数解决办法

发布时间: 2012-03-31 13:13:26 作者: rapoo

g关于map容器的count函数

C/C++ code
#include <iostream>#include <string>#include<map>using namespace std;int main(){      map<string,int> word_count;string word,word2;while(cin>>word)++word_count[word];cout<<"输入你统计的元素"<<endl;cin.clear();cin>>word2;cout<<word_count.count(word2)<<endl;return 0;} 

为什么我输入了N次的AAA,然后count AAA出现的次数 结果还是1次呢?

[解决办法]
被LZ欺骗了
size_type count ( const key_type& x ) const;Count elements with a specific key
Searches the container for an element with a key of x and returns the number of elements having that key.

这个成员函数是计算对应的key有多少个。而不是输出与key对应的value的。
[解决办法]
word_count.count(word2)
此句计算的是map容器中aaa的数量,而不是second的int值

读书人网 >C++

热点推荐