首页主机资讯c++ qsort如何使用

c++ qsort如何使用

时间2025-09-27 02:54:03发布访客分类主机资讯浏览1006
导读:qsort是C++中用于对数组进行排序的库函数,它需要用户自定义比较函数来确定元素之间的顺序 #include <iostream> #include <algorithm> // 包含 qsort 函数的头文件...

qsort是C++中用于对数组进行排序的库函数,它需要用户自定义比较函数来确定元素之间的顺序

#include <
    iostream>
    
#include <
    algorithm>
 // 包含 qsort 函数的头文件

// 自定义比较函数,用于比较两个整数的大小
int compare(const void *a, const void *b) {
    
    int int_a = *(int*)a;
    
    int int_b = *(int*)b;
    

    if (int_a <
 int_b) {
    
        return -1;
     // 如果 a <
 b,返回 -1
    }
     else if (int_a >
 int_b) {
    
        return 1;
     // 如果 a >
 b,返回 1
    }
 else {
    
        return 0;
 // 如果 a == b,返回 0
    }

}


int main() {

    int arr[] = {
5, 3, 8, 1, 6}
    ;
     // 整数数组
    int n = sizeof(arr) / sizeof(arr[0]);
     // 计算数组长度

    qsort(arr, n, sizeof(int), compare);
     // 使用自定义比较函数对数组进行排序

    std::cout <
    <
     "Sorted array: ";
    
    for (int i = 0;
     i <
     n;
 i++) {
    
        std::cout <
    <
     arr[i] <
    <
     " ";

    }
    
    std::cout <
    <
     std::endl;
    

    return 0;

}
    

在这个示例中,我们首先定义了一个名为compare的自定义比较函数,它接受两个指向void类型的指针作为参数。然后,我们使用qsort函数对整数数组arr进行排序,并将自定义比较函数作为参数传递给它。最后,我们遍历并输出排序后的数组。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c++ qsort如何使用
本文地址: https://pptw.com/jishu/709380.html
c++ qsort和sort区别 在linux怎样安装rust

游客 回复需填写必要信息