温馨提示×

如何处理c++中is_sorted函数的返回值

c++
小樊
81
2024-09-15 18:12:05
栏目: 编程语言

std::is_sorted 是 C++ 标准库中的一个函数,用于检查一个范围内的元素是否已按非降序排列。如果该范围内的所有元素都满足这一条件,则函数返回true;否则返回 false`。

以下是一个简单的示例,展示了如何使用 std::is_sorted 函数并处理其返回值:

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

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

    // 使用 std::is_sorted 检查向量是否已排序
    bool is_sorted = std::is_sorted(v.begin(), v.end());

    // 处理返回值
    if (is_sorted) {
        std::cout << "The vector is sorted."<< std::endl;
    } else {
        std::cout << "The vector is not sorted."<< std::endl;
    }

    return 0;
}

在这个示例中,我们创建了一个包含整数的 std::vector,然后使用 std::is_sorted 函数检查它是否已排序。接下来,我们根据函数的返回值输出相应的信息。如果向量已排序,将输出 “The vector is sorted.”,否则输出 “The vector is not sorted.”。

0