C++学习笔记——pair与map遍历深究

来源:互联网 发布:vep视觉训练软件 编辑:程序博客网 时间:2024/06/05 16:29

之前发过一篇 map 和 set 的组合使用的例子,进行排除常见单词的重复单词计数,这个例子中还有一些很多需要思考的问题
例子如下:

#include<iostream>#include<string>#include<map>using namespace std;int main(){    map<string,size_t> word_count;    string word;    while(cin>>word)    {        ++word_count[word];    }        for(const auto &w:word_count)        cout<<w.first<<" occurs "<<w.second<<((w.second>1?" times":" time"))<<endl;        system("pause");        return 0;}

比如

 for(const auto &w:word_count)

这个语句涉及到C++11新标准的 使用基于范围的for语句 在C++ primer的 83页可以找到详细的论述
例如当 word_cout是string型的时候,w就是char型,在这里 word_count是map型,所以w就是pair型,当然我们可以利用auto语句来进行自动的类型识别。
此外纠结了一晚上的疑问还有为什么必须写 w.first 而不能直接写 word_count.first
思考之后的结果是
因为w是map中的元素,所以是pair型的,pair型才可以写成 w.first
而word_count是map型的,map型的元素的遍历 需要定义一个迭代器iterator :: itr,并用itr->first或者itr->second

0 0
原创粉丝点击