c++ - 使用 std::lower_bound() 打印低于特定值的元素范围

标签 c++ stl

我有一个 vector 数组,其中填充了一些双 vector 值。我想打印 2.0 以下的所有数字。我的限制是,我必须使用 std::lower_bound()。如何才能做到这一点?这是我尝试使用的最小工作代码,但它只提供单个值:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    const double data[] = { 5.3, 9.2, 7.5, 6.9, 4.5 };
    const int dataCount = sizeof(data) / sizeof(data[0]);
    vector<double> vec(data, data + dataCount);
    sort(vec.begin(), vec.end());

    auto less2 = lower_bound(vec.begin(), vec.end(), 2.0);
    auto less4 = lower_bound(vec.begin(), vec.end(), 4.0);
    auto less6 = lower_bound(vec.begin(), vec.end(), 6.0);
    cout << "\nLess than 2.0 : " << *less2 << endl << "Less than 4.0  : " << *less4 << endl << "Less than 6.0  : " << *less6 << endl;
    return 0;
}

问候。

最佳答案

来自 cppreference/lower_bound :

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.

因此,如果要打印2.0以下的所有元素,需要从begin(vec)迭代到std::lower_bound返回的迭代器:

auto less2 = lower_bound(vec.begin(), vec.end(), 2.0);
for(auto it = begin(vec); it != less2; ++it) cout << *it << " ";

关于c++ - 使用 std::lower_bound() 打印低于特定值的元素范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41037034/

相关文章:

c++ - 数组打印出错误的数字

c++ - 性能:类的 vector 或包含 vector 的类

c++ - 如何正确地将变量传递给线程中的lambda函数

C++ kbhit 与 if 语句滞后

c++ - 在不知道字符串宽度的情况下左右对齐

c++ - 使用 std::strings 和 std::vectors 将值插入 std::map 时遇到问题

c++ - 为原始类型重载 operator<<。那可能吗?

c++ - 对象指针 vector 上的 vector::erase() 会破坏对象本身吗?

c++ - double vector 的 Python swig-wrapped vector 显示为元组

C++比较两个对象