关联容器和顺序容器有着根本的不通过:关联容器中的元素是按关键字来保存和访问的。与之相对,顺序容器中的元素是按他们在容器中的位置来顺序保存和访问的。关联容器支持高效的的关键字查找和访问。两个主要的关联容器类型时map和set。
类型map和multimap定义在头文件map中;set和multimultiset定义在头文件set中;无序容器则定义在头文件unordered_map和unordered_set中。
map:
map是关键字-值对的集合。例如,可以将一个人的名字作为关键字,将其电话号码作为值。我们称这样的数据结构为“将名字映射到电话号码”。map类型通常被称为关联数组。
下面是一个使用关联数组的例子:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string,size_t> word_count; //string到size_t的空map
string word;
int num = 0;
while (cin >> word) //从输入缓冲读入word
{
++word_count[word]; //提取word的计数器并加 1
if ( num++ == 9 ) //读取十个字符串
break;
}
for (const auto &w : word_count)
cout << w.first << "出现" << w.second << "次" << endl;
return 0;
}
顺便提供两种初始化map的方法:
//直接赋值法
map<string, int> m1;
m1[string("abc")] = 1;
m1[string("def")] = 2; //要格外注意中括号内的写法,字符串除了双引号,还要用小括号包起来!!
//用insert添加
map<string, int> m2;
m2.insert({ string("abc"), 1 });
m2.insert(make_pair(string("def"), 2));
m2.insert(pair<string, int>(string("ghi"), 3));
set:
与其他容器类似,set也是模板。定义了一个set,必须指定其元素类型,本例中是string,与顺序容器类似,可以对一个关联容器的元素进行列表初始化。上面示例程序使用set扩展,忽略常见单词,如“the”、“and”等,我们可以使用set保存箱忽略的单词,只对不在集合中的单词统计出现次数:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string,size_t> word_count; //string到size_t的空map
set<string> exclude = {"the","but","and","or"};
string word;
int num = 0;
while (cin >> word) //从输入缓冲读入word
{
if (exclude.find(word) == exclude.end()) //判断读入单词是否在set容器中
++word_count[word]; //提取word的计数器并加 1
if ( num++ == 9 ) //读取十个字符串
break;
}
for (const auto &w : word_count)
cout << w.first << "出现" << w.second << "次" << endl;
return 0;
}
这是简单用法,可以帮助理解map和set,具体的含义和深入解析在后面的博客再做深入探讨和解析