阅读量:81
在 C++ 中,std::is_sorted 函数用于检查一个序列是否已经按升序排序
以下是一个示例,展示了如何为 std::is_sorted 提供自定义比较函数:
#include
#include
#include
// 自定义比较函数
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 class="hljs-keyword">else {
std::cout << "The vector is not sorted in descending order."<< std class="hljs-keyword">return 0;
}
在这个示例中,我们创建了一个名为 my_compare 的自定义比较函数,该函数用于降序排序。然后,我们将此自定义比较函数传递给 std::is_sorted 函数,以检查向量 v 是否已按降序排序。