如何自定义比较函数用于c++的is_sorted

   2024-09-30 7130
核心提示:在 C++ 中,std::is_sorted 函数用于检查一个序列是否已经按升序排序以下是一个示例,展示了如何为 std::is_sorted 提供自定义比

在 C++ 中,std::is_sorted 函数用于检查一个序列是否已经按升序排序

以下是一个示例,展示了如何为 std::is_sorted 提供自定义比较函数:

#include<iostream>#include<vector>#include<algorithm>// 自定义比较函数bool my_compare(int a, int b) {    return a > b; // 降序排序}int main() {    std::vector<int> v = {5, 3, 1};    // 使用自定义比较函数检查是否已排序    bool is_sorted = std::is_sorted(v.begin(), v.end(), my_compare);    if (is_sorted) {        std::cout << "The vector is sorted in descending order."<< std::endl;    } else {        std::cout << "The vector is not sorted in descending order."<< std::endl;    }    return 0;}

在这个示例中,我们创建了一个名为 my_compare 的自定义比较函数,该函数用于降序排序。然后,我们将此自定义比较函数传递给 std::is_sorted 函数,以检查向量 v 是否已按降序排序。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号