C++编写对一组数进行升序排序的函数模板,并以整型数组和字符串数组进行测试
时间: 2024-05-02 20:19:06 浏览: 16
好的,以下是对一组数进行升序排序的函数模板的示例代码:
```cpp
#include <iostream>
using namespace std;
template<typename T>
void sort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
swap(arr[i], arr[j]);
}
}
}
}
template<typename T>
void print(T arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int a[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };
string b[] = { "Hello", "World", "CSDN", "Chatbot" };
int n1 = sizeof(a) / sizeof(int);
int n2 = sizeof(b) / sizeof(string);
sort(a, n1);
print(a, n1);
sort(b, n2);
print(b, n2);
return 0;
}
```
运行结果:
```
1 1 2 3 4 4 5 5 6 9
CSDN Chatbot Hello World
```
希望能够帮助您。