c++11 反向迭代器和 lower_bound
c++11 reverse iterator and lower_bound
我有以下示例程序:
#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()
编辑的迭代器 return 不是双向迭代器吗?
第二个问题是为什么a.lower_bound(6)->first
return是8而不是5?基于https://en.cppreference.com/w/cpp/container/map/lower_bound,它应该return一个指向第一个元素"not less than key"的迭代器。所以我认为 5 会被 returned,因为 8 > 6.
--a.rbegin()是一个UB。
lower_bound(val)
returns 指向范围内第一个比较不小于 val
的元素的迭代器。 5
不是 "not less than 6
" 所以你得到迭代器到 8
正确
我有以下示例程序:
#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()
编辑的迭代器 return 不是双向迭代器吗?
第二个问题是为什么a.lower_bound(6)->first
return是8而不是5?基于https://en.cppreference.com/w/cpp/container/map/lower_bound,它应该return一个指向第一个元素"not less than key"的迭代器。所以我认为 5 会被 returned,因为 8 > 6.
--a.rbegin()是一个UB。
lower_bound(val)
returns 指向范围内第一个比较不小于 val
的元素的迭代器。 5
不是 "not less than 6
" 所以你得到迭代器到 8
正确