一切尽在标题中。
考虑以下代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <typeinfo>
using namespace std;
int main(){
const int n=12;
double x[n];
x[0]=-0.717778;
x[1]=-0.496843;
x[2]=-0.429063;
x[3]=-0.3596;
x[4]=-0.205607;
x[5]=0.0730536;
x[6]=0.138018;
x[7]=0.585526;
x[8]=2.40104;
x[9]=3.752680001; //here
x[10]=3.75268;
x[11]=4.55704;
std::cout << std::is_sorted(x,x+n) << std::endl;
}
基本上,我希望它返回 1(表示真):
虽然我可以看到 x[9]
大于 x[10]
,
它们之间的差异小于 1e-8
所以我认为它们是相等的。
最佳答案
我会使用 (C++14):
std::adjacent_find(
std::begin(x),
std::end(x),
[epsilon](const auto& lhs, const auto& rhs) { return lhs > rhs + epsilon;})
== std::end(x);
因为 is_sorted
会产生误导。
或者在 C++11 中:
std::adjacent_find(
std::begin(x),
std::end(x),
[epsilon](const double& lhs, const double& rhs) { return lhs > rhs + epsilon;})
== std::end(x);
关于c++ - 使用 std::is_sorted 测试数组,但具有预设精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25622971/