首页 > 解决方案 > 未排序向量上的 lower_bound/upper_bound

问题描述

const std::vector<int> v = {5, 7, 3, 6, 5, 4, 7, 8, 5, 6};

auto low = std::lower_bound( v.begin(), v.end(), 7);
auto high = std::upper_bound( v.begin(), v.end(), 7);
std::cout << low - v.begin() << " " << high - v.begin();

因此,当我尝试在我的 Mac 上使用 clang++ 编译器编译此代码时,它会将输出返回为

10 10

这意味着v.end()高和低虽然低应该是 = 1 和高 = 7(数字 8)。我究竟做错了什么?

标签: c++stl

解决方案


std::lower_boundstd::upper_bound要求范围是“排序的”(实际上根据谓词和给定值进行分区),这不是你的情况。


推荐阅读