在 C++ 中,可以使用模板来实现任意类型的数组排序。具体代码如下:

#include <iostream>
#include <string>
using namespace std;

template <typename T>
void bubbleSort(T arr[], int len, bool asc=true)
{
    for(int i=0; i<len-1; i++)
    {
        for(int j=0; j<len-i-1; j++)
        {
            if((asc && arr[j]>arr[j+1]) || (!asc && arr[j]<arr[j+1]))
            {
                swap(arr[j], arr[j+1]);
            }
        }
    }
}

struct Book {
    string title;
    double price;
    int pages;
};

int main()
{
    int intArr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
    double doubleArr[] = {3.14, 1.41, 2.72, 0.62, 6.28};
    Book bookArr[] = {
        {"C++ Primer", 49.99, 1392},
        {"Data Structures and Algorithms", 29.99, 672},
        {"Effective C++", 39.99, 320},
        {"The C Programming Language", 34.99, 272},
        {"Design Patterns", 59.99, 416}
    };
    int intLen = sizeof(intArr)/sizeof(int);
    int doubleLen = sizeof(doubleArr)/sizeof(double);
    int bookLen = sizeof(bookArr)/sizeof(Book);

    bubbleSort(intArr, intLen);
    bubbleSort(doubleArr, doubleLen, false);
    bubbleSort(bookArr, bookLen, true);

    cout << "Sorted int array: ";
    for(int i=0; i<intLen; i++)
    {
        cout << intArr[i] << " ";
    }
    cout << endl;

    cout << "Sorted double array: ";
    for(int i=0; i<doubleLen; i++)
    {
        cout << doubleArr[i] << " ";
    }
    cout << endl;

    cout << "Sorted book array: " << endl;
    for(int i=0; i<bookLen; i++)
    {
        cout << bookArr[i].title << " " << bookArr[i].price << " " << bookArr[i].pages << endl;
    }

    return 0;
}

main 函数中,我们首先定义了三个不同类型的数组,分别是 int 数组、double 数组和 Book 数组。然后通过 sizeof 运算符计算出数组的长度,调用 bubbleSort 函数进行排序。对于 intdouble 数组,我们可以使用默认的升序排列;对于 Book 数组,我们需要按照价格升序排列,因此将第三个参数设置为 true

在输出结果时,我们分别遍历每个数组,打印出排序后的结果。可以看到,使用模板函数 bubbleSort 可以方便地对任意类型的数组进行排序。

C++ 通用冒泡排序函数:排序任意类型数组

原文地址: https://www.cveoy.top/t/topic/nXhG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录