16 STL集合和映射容器set/multiset_map/multimap(学自Boolean)

来源:互联网 发布:汉宁窗 c语言 编辑:程序博客网 时间:2024/05/29 09:12

1、概述

与序列容器sequence container不同,set/multiset,map/multimap是关联容器associate container。其中set与multiset、map与multimap的区别是前者是不能有重复元素,后者可以存放重复元素,本篇只介绍可以存放重复元素的multiset和multimap容器。

2、multiset容器

1)容器的结构

说明:set和multiset是二叉树的结构,实际上是红黑数。

2)multiset声明和元素添加

#include <set>#include <string>#include <iostream>#include <ctime>#include <cstdio>using namespace std;using std::string;multiset<string> c;char buf[10];srand((unsigned)time(NULL));for (long i = 0; i < value; ++i){_snprintf(buf, 10, "%d", rand());c.insert(string(buf));}
注意点:

a、头文件使用#include <set> 引入multiset或set容器;

b、multiset容器插入元素,使用insert()方法。

3)multiset元素查找

string target = get_a_target_string();auto pItem = ::find(c.begin(), c.end(), target); //全局循序查找,速度慢if (pItem != c.end()){cout << "found, " << *pItem << endl;}else{cout << "not found!" << endl;}auto pItem1 = c.find(target); //成员函数实现查找,速度快if (pItem1 != c.end()){cout << "found, " << *pItem1 << endl;}else{cout << "not found!" << endl;}
注意点:

a、查找multiset容器中元素的方式有两种,一种是通过全局find()方法,另一种是通过成员函数find()方法;

b、一般在能使用成员函数的查找方法时,就使用成员函数方法,效率快。

3、multimap容器

1)容器的结构


说明:multimap或map容器也是采用一种红黑树,只是容器的元素是通过键/值对存储的。

2)multimap容器的声明和元素插入

#include <map>#include <string>#include <ctime>#include <iostream>#include <cstdio>using namespace std;using std::string;multimap<long, string> c;char buf[10];srand((unsigned)time(NULL));for (long i = 0; i < value; ++i){_snprintf(buf, 10, "%d", rand());//multimap不可使用[]做insertion c.insert(std::pair<long, string>(i, buf));}
注意点:

a、头文件使用#include <map>引入multimap或map容器;

b、声明multimap容器,使用键/值对两个模板参数,multimap<long, string> c;

c、使用insert()方法向multimap中插入元素,其中元素使用模板库中的pair对象,刚好对象时满足键/值对的要求。

d、如果使用map容器,可以使用c[i] = string(buf)的方式添加元素。

3)multimap容器中查找元素

long target = get_a_target_long();auto pItem = c.find(target);if (pItem != c.end()){cout << "found, value = " << (*pItem).first << " " << (*pItem).second << endl;}else{cout << "not found!" << endl;}
注意点:

a、使用成员函数find()来查找元素;

b、元素查找后的输出使用解引用的方式,在使用 .xx的方式输出元素 如(*pItem).first。  

4、unordered_set/unordered_multiset和unordered_map/unordered_multimap容器

针对这4种容器,也是关联容器。下面只介绍下其结构。

1)unordered_set和unordered_multiset结构

说明:这是种无序的set容器形式,其实就是hashtable结构。

2)unordered_map和unordered_multimap结构

说明:这是种无序的map容器形式,其实也是一种hashtable结构。


原创粉丝点击