C++ STL: map & set


关联容器

关联容器链接

(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容器

总结

map set源代码分析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值