【发布时间】:2018-01-07 15:44:03
【问题描述】:
提问前:我明白std::map::lower_bound和std::map::upper_bound的意思
问题:如何获得指向 LAST 元素且不大于 key 的迭代器。
以下示例显示了lower_bound/upper_bound 的当前行为。
但是,我想要:
- 传入“20”,返回20
- 传入“25”,返回20
我怎样才能做到这一点?
#include <iostream>
#include <map>
int main ()
{
std::map<int,char> mymap;
std::map<int,char>::iterator itlow,itup;
mymap[10]='a';
mymap[20]='b';
mymap[30]='c';
mymap[40]='d';
mymap[50]='e';
itlow=mymap.lower_bound (20); // itlow points to 'b'
std::cout << "lower_bound for 20: " << itlow->first << " => " << itlow->second << '\n';
itup=mymap.upper_bound (20); // itup points to 'c'
std::cout << "upper_bound for 20: " << itup->first << " => " << itup->second << '\n';
itlow=mymap.lower_bound (25); // itlow points to 'c'
std::cout << "lower_bound for 25: " << itlow->first << " => " << itlow->second << '\n';
itup=mymap.upper_bound (25); // itup points to 'c'
std::cout << "upper_bound for 25: " << itup->first << " => " << itup->second << '\n';
return 0;
}
这是上面代码的执行结果。
lower_bound for 20: 20 => b
upper_bound for 20: 30 => c
lower_bound for 25: 30 => c
upper_bound for 25: 30 => c
【问题讨论】:
-
为什么不直接使用
upper_bound,然后将迭代器减一呢? (你必须检查它是否等于mymap.begin()) -
@rlbond 太棒了!
-
@rlbond 如果你把这个放在答案中,我会投票赞成:-)
标签: c++