关联容器
(1)map
#include<map>
using namespace std;
//pair类型
#include <utility>
pair<string, string> p1("John", "Jack")
pair<string, string> p2{"John",
"Jack"}
//初始化方法
map<string, size_t> word_count;
map<string, string> author1 = {{"Joyce", "James"}, {"Austen", "Jane"}};
map<string, string> author2 = author1;
//map容器额外的类型别名
map<string, int>::value_type v1;//v1是pair<const string ,int>
map<string, int>::key_type v2;//v2是string,即key类型
map<string, int>::mapped_type v3;//v3是value的type,即int
//常用方法
//添加元素只能用insert, emplace
map<string, size_t> word_count;
string word("fesf");
word_count.insert({word,1});
//等价于
word_count.insert(pair<string, size_t>::value_type(word,1));
word_count.insert(pair<string, size_t>(word, 1));
word_count.emplace(word, 1);
//遍历map容器(const iterator)
for(auto map_it = word_cout.cbegin(); map_it != word_cout.cend(); map_it++)
cout<< map_it->first<<':' <<map_it->second<<endl;
//下标操作[] 添加元素
word_count["Anna"] = 1;
//访问元素
c.find(key);//返回关键字为key的迭代器,如果不存在则返回c.end(
c.count(key);//返回关键字等于key的元素数量,由于map关键字不允许重合,返回永远为0或者1
c.size();
c.empty();
//删除元素
c.erase(key);//删除关键字为key的元素
c.erase(iter);//删除迭代器指定元素
c.erase(b_iter, e_iter);//删除范围中的元素
(2)multimap
很多操作和map相同,但是关键字不必唯一
multimap<string, string> authors;
//插入元素
authors.insert({"Barth","sot-weed factor"});
//添加第二个元素,关键字也是Barth
authors.insert({"Barth","Lost in the Funhouse"});
//不支持下标操作!!!一个关键字可能对应多个值
//查找元素:重复元素在容器中相邻存储,通过循环全部找出
string search_item("Alain");
int numbers=authors.count(search_item);
auto it=authors.find(search_item);
while(numbers)
{
cout<<iter->second<<endl;
++it;
numbers--;
}
(3)set
set默认排序好了
#include<set>
//初始化
set<string> a1 = {"sfs", "55"};
set<string> a2 = a1;
//添加和删除元素
set<string> a;
a.insert("fengxin");
a.emplace("124");
//
a.erase("123");
a.clean();
//遍历
set<int> iset={0,1,2,3,4,5,6,7,8,9};
for(auto iter = iset.begin(); iter != iset.end(); iter++)
cout<< *iter <<endl;
//不支持下标操作
iset.count(key); //0 or 1
auto it = iset.find(key);//用关键字查找
cout<<*it;
(4)multiset
- set和multiset容器区别同map与multimap容器