我有以下示例程序:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<int, int> a;
a[8] = 1;
a[5] = 1;
a[1] = 1;
a[2] = 1;
std::cout << a.begin()->first << std::endl;
std::cout << a.rbegin()->first << std::endl;
std::cout << (++a.rbegin())->first << std::endl;
std::cout << (--a.rbegin())->first << std::endl;
std::cout << (a.lower_bound(6))->first << std::endl;
}
当我执行它时,我得到这个输出:
1
8
5
5
8
我有两个问题。首先是为什么++a.rbegin()
和--a.rbegin()
迭代的方向相同? a.rbegin()
返回的迭代器不是双向迭代器吗?
第二个问题是为什么 a.lower_bound(6)->first
返回 8 而不是 5?基于https://en.cppreference.com/w/cpp/container/map/lower_bound ,它应该返回一个迭代器到第一个元素“不小于键”。所以我原以为 5 会被返回,因为 8 > 6。
最佳答案
--a.rbegin() 是一个 UB。
lower_bound(val)
返回指向范围内第一个不小于 val
的元素的迭代器。 5
不是“不小于 6
”,因此您可以正确地将迭代器设置为 8
关于c++11 反向迭代器和 lower_bound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978043/