c++ - 使用 std::lower_bound

标签 c++

// 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/

相关文章:

c++ - ListView 在 mfc 中杀死焦点

c++ - 使用父模板类的非依赖嵌套类作为子类中的成员

c++ - 'using' 关键字与多个重载

C++:当两个类包含指向另一个类的指针时,如何解决派生类之间的模板循环依赖?

c++ - C++ 字符串的通用库

c++ - 程序接受非数字输入,我如何让它停止这样做?

c++ - 如何在 C++ win32 中写入文件? (对比 2010)

android - 如何知道我正在为使用 ndk-build 构建哪个 API 级别?

android - C++ WinSock 蓝牙连接 - AT 命令 - 收到错误

c++ - 无法在 kernel32.dll 中找到 GetOverlappedResultEx