按关键字有序保存元素
#include <map>
//关联数组map:保存关键字-值对应
//multimap:关键字可重复出现的map
初始化
//建议使用make_pair构建
map<string, int>mp = {{"aa", 1}, {"aaa", 2}, {"22", 33}};//必须用{key, value}包含起来
map容器元素
pair<string, int>p("aa", 1);
pair<string, int>p={"aa", 1};
插入
/*
插入时可以是无序的
容器会根据下标由大到小自动调整顺序
*/
mp.insert({ s2,b });//建议使用
mp.emplace(s2, b);
mp.insert(make_pair(s2, b));
mp.insert(p);
mp.insert(mp2.begin(), mp2.end());//范围插入
auto ret = mp.insert(mp.end(), { "g",7 });
auto ret2 = mp.insert({ s2,b });
insert的返回值
map<string, size_t>mp;
string word;
while (cin >> word)
/*等价于while()循环里面的所有操作
由于插入的元素出现重复的话不会进行insert插入操作*/
//++mp.insert({ word,0 }).first->second;
{
auto ret = mp.insert({ word,1 });
/*
pair<map<string, size_t>::iterator, bool> ret = mp.insert({ word,1 });
insert返回1个pair类型,first为指向该被插入元素的迭代器
second为bool,要插入的关键字已经在map中,为false,反之为true
对于multimap直接返回指向该被插入元素的迭代器
*/
if (!ret.second)//出现重复
++ret.first->second;//对map中对应的元素的内容+1
}
大小比较
1.依次比较first和second成员
2.两个比较的关系为与
3.记得带括号
cout << (p2 < p3) << endl;
cout << (p2 == p3) << endl;
cout << (p2 != p3) << endl;
set
#include <set>
//关键字既值set,既只保存关键字的容器
//multiset:关键字可重复出现的set
1.只存储关键字
2.只读
set<int>iset = { 0,1,2 };
iset.insert({ 1,2,3,4,5,6,7 });
//迭代器
auto set_it = iset.begin();
cout << *set_it << endl;
set<int>iset = { 0,1,2 };
int num = 2;
//找到后会返回指向该关键字的迭代器,否则返回尾后迭代器
if (iset.find(num) == iset.end())
auto map_it = mp.begin();
while (map_it != mp.end())
cout << map_it->first << map_it->secod << endl;
map<int, int>mp = { { 1,1 },{ 2,2 },{ 3,3 },{ 4,4 },{ 5,5 },{ 6,6 } };
size_t ret1 = mp.erase(2);//删除关键字为2的pair,返回被删除的个数
auto ret2 = mp.erase(mp.begin());//删除迭代器指向的pair,返回指向下一个元素
auto ret3 = mp.erase(mp.begin(), --mp.end());//删除范围不包括--mp.end(),返回--mp.end()
删除返回迭代器所指向的内容在被删除后依然不会失效(可以用下面的代码检验)
cout << "ret1:" << ret1 << endl;
cout << "ret2:" << ret2->first << " " << ret2->second << endl;
cout << "ret3:" << ret3->first << " " << ret3->second << endl;
下标操作
1.map和unordered_map支持
2.set,multimap和unordered_multimap不支持下标
mp[9] = 3;//如果下标(关键字)不存在,会自动插入该元素
mp.at(3) = 2;
访问
1.类pair有两个public成员
2.first为关键字,类似于数组的下标,初始化后无法改变
3.second为数组的内容
for (const pair<int, int>&p : mp)//因为pair的键值是const的,所以范围for引用必须要加const
cout << p.first << " " << p.second << endl;
map<int, int>mp = { { 1,1 },{ 2,2 },{ 3,3 },{ 4,4 },{ 5,5 } };
auto ret1 = mp.find(1);//返回一个迭代器
auto ret2 = mp.find(11);//未找到,返回迭代器=mp.end();
auto ret3 = mp.count(1);//返回数量
auto ret4 = mp.count(11);
auto ret5 = mp.lower_bound(2);//返回的迭代器指向第一个关键字大于等于2的元素。
auto ret6 = mp.upper_bound(3);//返回的迭代器指向第一个关键字大于3的元素
multimap<int, int>mmp = { { 1,1 },{ 1,1 },{ 2,2 },{ 1,1 } };
/*
返回一个pair
first和second里面存储的都是关键字为1的范围
*/
auto it = mmp.equal_range(1);
for (auto i = it.first; i != it.second; ++i)
//输出3个1,1
cout << i->first << " " << i->second << endl;
对于multimap,lower_bound和upper_bound可以代替equal_bound
for (auto beg = mmp.lower_bound(1), end = mmp.upper_bound(1); beg != end; ++beg)
cout << beg->first << " " << beg->second << endl;