c++

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

小樊
89
2024-09-15 18:05:58
栏目: 编程语言
C++开发者专用服务器,限时0元免费领! 查看>>

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.

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:c++中is_sorted函数的参数有哪些

0
看了该问题的人还看了