STL map 的 lower_bound(x)、upper_bound(x) 等常用函数
【STL map 简介】
● STL map 是一种关联容器,存储键值对,每个键(key value)是唯一的,而值(mapped value)可以重复。构建 STL map 时,无论元素插入顺序如何,STL map 中的元素始终按“键值”自动递增存储。STL map 中的迭代器可理解为“指针”。
#include <bits/stdc++.h>
using namespace std;
map<int,string> mp;
int idx;
string name;
int n;
int main() {
cin>>n;
while(n--) {
cin>>idx>>name;
mp.insert({idx,name});
}
for(auto it=mp.begin(); it!=mp.end(); it++) {
cout<<it->first<<":"<<it->second<<endl;
}
return 0;
}
/*
in:
5
3 Java
1 C++
9 Python
8 R
6 SQL
out:
1:C++
3:Java
6:SQL
8:R
9:Python
*/
● STL map 常用函数的功能与 STL set 常用函数的功能基本一致。
(1)lower_bound(x):返回一个迭代器,该迭代器指向第一个大于等于 x 的元素。若无,返回 end() 得到的迭代器。
(2)upper_bound(x):返回一个迭代器,该迭代器指向第一个大于 x 的元素。若无,返回 end() 得到的迭代器。
(3)find(x):返回一个迭代器,该迭代器指向“键 x”所在的元素。
(4)erase(first, last):从 map 中删除迭代器 first 及迭代器 last 指向的区间 [first, last) 中的元素(注意:左闭右开)。
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int,string> mp= {{9,"a"}, {7,"b"}, {2,"c"}, {6,"d"}};
auto first=mp.find(2);
auto last=mp.find(7);
mp.erase(first,last);
for(auto it=mp.begin(); it!=mp.end(); it++) {
cout<<it->first<<":"<<it->second<<endl;
}
return 0;
}
/*
output:
7:b
9:a
*/
(5)begin():返回一个迭代器,该迭代器指向 map 第一个元素的位置。
(6)end():返回一个迭代器,该迭代器指向 map 最后一个元素的下一个位置。
(7)count(x):返回 map 中“键” x 的个数。
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int,string> mp= {{6,"apple"},{8,"banana"}};
cout<<mp.count(6)<<endl; //output 1
cout<<mp.count(5)<<endl; //output 0
return 0;
}
由于 map 中所有“键”的个数都是唯一的,所以若 x 在 map 中,返回 1,若 x 不在 map 中,返回 0。
【参考文献】
https://cplusplus.com/reference/map/map/
https://cplusplus.com/reference/map/map/count/
https://cplusplus.com/reference/map/map/lower_bound/
https://cplusplus.com/reference/map/map/upper_bound/
https://cplusplus.com/reference/map/map/insert/
https://cplusplus.com/reference/map/map/erase/
https://cplusplus.com/reference/map/map/begin/
https://www.cnblogs.com/linxiaoxu/p/17694869.html