C++学习笔记——pair与map遍历深究
2016-08-04 10:59
435 查看
之前发过一篇 map 和 set 的组合使用的例子,进行排除常见单词的重复单词计数,这个例子中还有一些很多需要思考的问题
例子如下:
比如
这个语句涉及到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
例子如下:
#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
相关文章推荐
- C++学习笔记-----std::pair作为unordered_map的key
- c++学习笔记-map的使用实例(单词转换)
- c++ 模板学习笔记:类模板和函数模板实现pair(权哥)
- C++ map容器 学习笔记
- C++学习笔记---再探 map 的用法之计数重复key的value值的方法,由leetcode 169题想到的
- C++学习笔记--STL(映射:map)
- C++ map学习笔记
- c++学习笔记 map
- Java学习笔记(八):Map<stirng,string>的遍历的四种方法
- C++ STL关联容器 set和map学习笔记
- C++学习笔记——Mat类详解及元素的遍历方法
- 【C++学习笔记】 set里加入pair
- C++学习笔记-list遍历
- Android(java)学习笔记104:Map集合的遍历之键找值
- 【C++ 学习笔记】:STL-map
- C++ STL--map映照容器学习笔记
- C++ map容器 学习笔记
- 二叉树的遍历(c++学习笔记)
- C++学习笔记——map与set的组合使用
- C++学习笔记22——关联容器之map