// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
在这段代码中,有人可以解释为什么我们需要在倒数第三行和第四行执行 (low - v.begin()) 和 (up - v.begin())。
如果我这样做
cout << low << endl;
我收到以下我不理解的错误
cannot bind ‘std::ostream {aka std::basic_ostream}’ lvalue to ‘std::basic_ostream&&’
最佳答案
*low * 是您声明的迭代器。它包含您的 PC 生成的内存地址,您不需要返回任何内存地址。通过写作
low- v.begin()
您向程序发出命令以返回搜索查询的实际位置作为答案。
这就是为什么它返回一个值
Address Position - Beginning of the Vector Position
假设您的 vector 起始内存地址是 FFF1,并且您的搜索值是 FFF8 ... 然后它返回 FFF8 - FFF1 = 7 ..(示例只是为了说明)
我是这么理解的。
关于c++ - 使用 std::lower_bound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905539/