您的位置:首页 > 编程语言 > C语言/C++

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

2016-08-04 10:59 435 查看
之前发过一篇 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息