引用

关联容器提供高效的关键字查找和访问.两个主要的关联容器类型是mapset.

介绍

map:map中的元素是一些关键字-值对,即key-value.关键词起索引的作用,值则表示与索引相关联的数据.
set:set支持高效的关键字查询操作——检查一个给定的关键字是否在set中.

map使用示例

如下是map的使用示例:

#include <iostream>
#include <string>
#include <map>
#include <set>

using namespace std;

int main()
{
    map<string, size_t> word_count;
       //key     value     通过key来索引value
    string word;

    while(cin >> word)   //输入word
    {
        ++word_count[word];   //通过word索引到值 即通过word查找到size, 然后自增
    }

    for(const auto &w : word_count)    //用范围for循环输出
    {
        cout << w.first << " occurs " << w.second
            << ((w.second > 1)? " times" : " time") <<endl;
    }
    return 0;
}

运行截图

运行截图

set使用示例

#include <iostream>
#include <string>
#include <map>
#include <set>

using namespace std;

int main()
{
    map<string, size_t> word_count;
       //key     value     通过key来索引value

    set<string> exclude = {"the", "haha", "good"};  //此处定义set 且有3个值

    string word;

    while(cin >> word)
    {
        if(exclude.find(word) == exclude.end())   //end 尾后迭代器 表示未找到
            ++word_count[word];
    }

    for(const auto &w : word_count)
    {
        cout << w.first << " occurs " << w.second
            << ((w.second > 1)? " times" : " time") <<endl;
    }

    return 0;
}

运行截图

运行截图

类似这两个容器的还有multimap, multiset, unordered_map等等共8个关联容器类型.

最后修改:2019 年 08 月 19 日
如果觉得我的文章对你有用,请随意赞赏