c++ - 使用 std::is_sorted 测试数组,但具有预设精度

标签 c++ std

一切尽在标题中。

考虑以下代码:

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

相关文章:

c++ - 我想从一个有空格的文件中读取 C++ ifstream

c++ - 从文件缓冲区读取 6 个字节

c++ - openGL中具有大存储空间的文本文件

c++ - 是否有 std::tm 结构的替代方案?

c++ - 寻找具有下限的最近点......但数据未排序

c++ - C++03 中 C++ 枚举的底层类型

c++ - 如何实例化其构造函数需要来自包含类名的字符串的参数的对象?

c++ - 如何有效地计算顶部排列

C++:std::visit 不能在 gcc 下编译

c++ - 从仅包含其迭代器的列表中删除元素