我有一个 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;
}
问候。
最佳答案
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/