Design a sorting function template, and use integer, floating point and string sorting in the main function to verify. int main(x string Str[5]={"Zhang" "Li", "Wang" "Qian", "Liang"); it Int[4]={20,12,0,-5); double Dou[6]={11,3,5,6,10,-9}; Sort<string>(Str,5); Sort«int>(Int,4); Sort<double> (Dou,6); Print(Str,5); Print(Int,4); Print(Dou,6); return 0; 7
时间: 2024-01-30 07:02:57 浏览: 69
dianti.rar_SORTING IN VHDL_vhdl电梯三层
Sure, here's an example sorting function template that can be used to sort integers, floating point numbers, and strings:
```
#include <iostream>
#include <string>
template <typename T>
void Sort(T arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
if (arr[j] < arr[i]) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
template <>
void Sort<std::string>(std::string arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
if (arr[j] < arr[i]) {
std::string temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
template <typename T>
void Print(T arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
std::string Str[5] = {"Zhang", "Li", "Wang", "Qian", "Liang"};
int Int[4] = {20, 12, 0, -5};
double Dou[6] = {11, 3, 5, 6, 10, -9};
Sort<std::string>(Str, 5);
Sort<int>(Int, 4);
Sort<double>(Dou, 6);
Print<std::string>(Str, 5);
Print<int>(Int, 4);
Print<double>(Dou, 6);
return 0;
}
```
This function template takes in an array of elements of type `T` and sorts them in ascending order using a simple selection sort algorithm. There is a specialization for strings, since they cannot be compared using the `<` operator like integers and floating point numbers can.
In the `main` function, we create arrays of integers, floating point numbers, and strings, and call the `Sort` function template on each of them. We then print out the sorted arrays using another function template `Print`, which simply prints out the elements of the array separated by spaces.
阅读全文