c++

c++中is_sorted函数的作用是什么

小樊
82
2024-09-15 18:05:58
栏目: 编程语言

std::is_sorted 是 C++ 标准库` 中的一个函数,它用于检查一个范围内的元素是否已经按照非降序(即升序或相等)排列。

函数原型如下:

template< class InputIt >
bool is_sorted( InputIt first, InputIt last );

template< class InputIt, class Compare >
bool is_sorted( InputIt first, InputIt last, Compare p );

参数说明:

函数返回一个布尔值,如果范围内的所有元素都按照非降序排列,则返回 true;否则返回 false

示例:

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    if (std::is_sorted(v.begin(), v.end())) {
        std::cout << "The vector is sorted."<< std::endl;
    } else {
        std::cout << "The vector is not sorted."<< std::endl;
    }
    
    return 0;
}

输出:

The vector is sorted.

0
看了该问题的人还看了