下限误差
Lower bound error
本文关键字:误差 更新时间:2023-10-16
我在C++Lower_bound()
上学习本教程。我制作了一个简单的代码来查找向量中的一个数字,该向量小于或等于向量中的数字+我想要的任何数字。我的代码是这样的
cout << *lower_bound(A.begin(), A.end(), A[x] + 3);
对向量A[]
进行排序的位置。但是代码将其指向一个大于两个数字之和的数字。
例如,如果我的向量具有0, 3, 5, 8, 12
的值,并且我希望它打印小于或等于A[3] + 3 = 11
的最接近的数字,它应该给出8
输出,但它给出12
的输出。有什么原因吗?
这是我的代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> A = {0, 5, 3, 12, 8};
sort(A.begin(), A.end());
cout << "A[3] = " << A[3] << endl;
cout << *lower_bound(A.begin(), A.end(), A[3] + 3) << endl;
return 0;
}
lower_bound
返回一个迭代器,指向区域 [first,last( 中的第一个元素,该元素的比较不小于 val。
在您的情况下,它不会返回小于 11 的最后一个值。它返回第一个不小于 11 的值,在您的示例中为 12。
如果你希望最大的数字不大于你的目标,你可以使用std::greater<>
和反向迭代器(或按std::greater<>
排序(
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> A = {0, 5, 3, 12, 8};
std::sort(A.begin(), A.end());
std::cout << "A[3] = " << A[3] << std::endl;
std::cout << *std::lower_bound(A.rbegin(), A.rend(), A[3] + 3, std::greater<int>{}) << std::endl;
return 0;
}
相关文章:
- 为什么在浮点中从大到小会引入更多的误差
- 基于相邻元素 c++ 的分段误差范围的循环
- QImage::p ixel 和 QImage::setPixel 坐标超出范围误差
- 将误差线添加到 VTK 二维散点图
- 动态矩阵特征分解过程中的误差
- 转换为非标量误差是什么意思?我该如何解决?
- 特征误差:INVALID_MATRIX_PRODUCT乘向量和矩阵
- 使用不同参数匹配器的同一方法ON_CALL AND EXPECT_CALL会产生饱和和活动误差
- boost odeint 中的受控误差步进器是否支持复杂的数据类型?
- 此外,在计算大斐波那契数时存在精度误差
- C++17中不定参数函数的误差
- 多态性中独立类的基本误差.C++
- 犰狳函数的不同最小二乘误差
- 在 qt 中的绘图中拖动误差线
- variadic函数和折叠表达:试图在Visual Studio 2017中编译时致命误差
- 在Cython中使用移动方法时的汇编误差
- variadic模板代码中的GCC VS MSVC编译误差
- CMAKE和CUDA的权限误差
- OPENCV C 中的分割故障误差
- ROS中未定义的参考误差到OpenCV图像转换器