在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函数进行排序。对于int和double数组,我们可以使用默认的升序排列;对于Book数组,我们需要按照价格升序排列,因此将第三个参数设置为true。

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

C++编写一个函数用于给数组元素的数据类型指定为任意类型的数组进行冒泡排序该函数有三个参数一个用来传递需要排序的数组一个用来传递数组的长度最后用于指定排序方式true表示升序排序false表示降序排序。编写代码验证该函数是否可以给int数组、double数组甚至一组图书排序其中图书有标题、单价和总页数属性排序是按照价格排序的。

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

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