最近在工作中遇到了std::map中的lower_bound与upper_bound,再次记录下其功能和使用方式。
std::map<char, int> mp;
mp.lower_bound<key> : 返回的是第一个大于、等于key的iterator,如果没有则返回空。
mp.upper_bound<key> :返回的是第一个大于key的iterator,如果没有,则返回空
例子如下:
// map::lower_bound/upper_bound
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap = {{'a', 20}, {'b', 40}, {'c', 60}, {'d', 80}, {'e', 100}};
// 否则使用下面的赋值方式
#if 0
mymap['a']=20;
mymap['b']=40;
mymap['c']=60;
mymap['d']=80;
mymap['e']=100;
#endif
auto itlow = mymap.lower_bound('b'); // itlow points to b
auto itup = mymap.upper_bound('d'); // itup points to e (not d!)
std::cout << "itlow " << itlow->first << " => " << itlow->second << '\n';
std::cout << "itup " << itup->first << " => " << itup->second << '\n';
auto upper = mymap.upper_bound('e');
std::cout << "upper " << upper->first << " => " << upper->second << '\n';
mymap.erase(itlow,itup); // erases [itlow,itup)
std::cout << "print content " << '\n';
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
结果:
总结:
1、使用upper_bound(key)时,如果没有找到大于key的iterator时,返回为空
2、lower_bound(key)返回的是大于、等于key的iterator,如果没有,返回空。