到今天为止,C++ Primer已经学习了有将近四个月的时间,目前学习到12章的最后一节,这一节要实现一个文本查询程序,作为标准库相关内容的学习总结。然后看到程序的功能和如何实现的流程之后,完全不知所错,即是因为实在是经验太少,很少去写一些真正具有实际功能的程序或者算法,再一个是因为从前学习过的知识点不用就会忘掉。所以今天开始打算用博客的方式争取每天写一些C++学习中的痛点内容,来提升自己的编程水平,再一个是对原有的知识进行复习。
关联容器
关联容器与顺序容器有着根本的不同:关联容器中的顺序是按照关键字来保存和访问,而顺序容器是按照它们在容器中的位置顺序来保存和访问的。
关联容器支持高效的关键字查找和访问,两个主要的关联容器类型是map 和 set
map: key - value 元素方式,key起到索引的作用,value则表示与索引相关联的数据。
使用实例: 字典,单词为关键字,单词释义为value
set:只含有key,set支持高效的关键字查询操作,检查一个给定关键字是否在set中。
使用实例:在某些文体处理过程中,可以用一个set来保存想要忽略的单词。
每个map或者set都含有有序版和无序版,可重复版和不可重复版,一共有8个关联容器。
map 程序举例
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, size_t> word_count; //string到size_t的空map
string word;
while (cin >> word)
++word_count[word]; //提取word的计数器并将其加以
for (const auto &w : word_count) //打印结果
cout << w.first << " occurs " << w.second
<< ((w.second > 1) ? "times" : "time") << endl;
return 0;
}
测试代码![](https://i-blog.csdnimg.cn/blog_migrate/b588d7c7e0ee51e74f292190a34cd804.png)
set 程序举例
set的程序是根据上面的map程序通过set进行扩展。
我们在对单词计数的时候可以忽略一些单词,比如说“the”,“and”,“or”。如果想忽略这些单词,可以通过使用set数据结构来忽略他们。
find函数调用返回一个迭代器。如果给定关键字在set中,迭代器指向该关键字,否则find返回尾后迭代器。
#include <iostream>
#include <map>
#include <string>
#include <set>
using namespace std;
int main()
{
map<string, size_t> word_count; //string到size_t的空map
set<string> exclude = {"The", "But", "And", "Or", "An", "A",
"the", "but", "and", "or", "an", "a"};
string word;
while (cin >> word)
{
if(exclude.find(word) == exclude.end())
++word_count[word]; //提取word的计数器并将其加以
}
for (const auto &w : word_count) //打印结果
cout << w.first << " occurs " << w.second
<< ((w.second > 1) ? "times" : "time") << endl;
return 0;
}