溫馨提示×

如何自定義比較函數(shù)用于c++的is_sorted

c++
小樊
82
2024-09-15 18:09:42
欄目: 編程語言

在 C++ 中,std::is_sorted 函數(shù)用于檢查一個序列是否已經(jīng)按升序排序

以下是一個示例,展示了如何為 std::is_sorted 提供自定義比較函數(shù):

#include<iostream>
#include<vector>
#include<algorithm>

// 自定義比較函數(shù)
bool my_compare(int a, int b) {
    return a > b; // 降序排序
}

int main() {
    std::vector<int> v = {5, 3, 1};

    // 使用自定義比較函數(shù)檢查是否已排序
    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;
}

在這個示例中,我們創(chuàng)建了一個名為 my_compare 的自定義比較函數(shù),該函數(shù)用于降序排序。然后,我們將此自定義比較函數(shù)傳遞給 std::is_sorted 函數(shù),以檢查向量 v 是否已按降序排序。

0