设计排序函数模版和数组显示函数模版,编写测试程序,;利用函数模版,分别完成整数型数组排序和字符串数组排序,再利用数组显示函数模版,完成整型数组和字符串数组的输出
时间: 2023-07-16 22:17:25 浏览: 63
下面是一个可能的实现:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
template<typename T>
void displayArray(const T* arr, int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
template<typename T>
void sortArray(T* arr, int size) {
std::sort(arr, arr + size);
}
int main() {
int intArray[] = { 4, 2, 1, 3 };
std::string strArray[] = { "apple", "banana", "cherry", "date" };
int intSize = sizeof(intArray) / sizeof(int);
int strSize = sizeof(strArray) / sizeof(std::string);
std::cout << "Before sorting:" << std::endl;
displayArray<int>(intArray, intSize);
displayArray<std::string>(strArray, strSize);
sortArray<int>(intArray, intSize);
sortArray<std::string>(strArray, strSize);
std::cout << "After sorting:" << std::endl;
displayArray<int>(intArray, intSize);
displayArray<std::string>(strArray, strSize);
return 0;
}
```
这个程序定义了两个函数模板,`displayArray` 和 `sortArray`,分别用于数组显示和排序。`displayArray` 接受一个指向数组的指针和数组的大小作为参数,然后遍历数组并输出每个元素。`sortArray` 利用 `<algorithm>` 头文件中的 `std::sort` 函数对数组进行排序。
在 `main` 函数中,我们定义了两个数组,一个整型数组和一个字符串数组,然后计算它们的大小。我们使用 `displayArray` 显示数组中的元素,然后使用 `sortArray` 对数组进行排序。最后,我们再次使用 `displayArray` 显示排序后的数组。注意,在调用函数模板时需要指定类型参数。