编制如下两个函数模板,用于完成所指定的功能;并编制主函数对它们进行调用: template <class T> Print(T *p, int n) {...} template <class T> void GtLever(T *p, int n, T lever){...} 其中,函数模板Print将数组p的前n个元素显示在屏幕上;函数模板Gtlever将p数组前n个元素中大于lever的各个元素, 依次移动到该数组的最前部,而后通过调用Print将p中大于lever的各元素显示在屏幕上。对于cha
时间: 2024-02-06 12:10:49 浏览: 29
r类型的数组,Print函数应该按照字符方式输出;对于其他类型的数组,Print函数应该按照数值方式输出。
以下是代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
void Print(T *p, int n);
template <>
void Print<char>(char *p, int n);
template <class T>
void GtLever(T *p, int n, T lever);
template <>
void GtLever<char>(char *p, int n, char lever);
int main() {
int a[5] = {1, 2, 3, 4, 5};
double b[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
char c[5] = {'a', 'b', 'c', 'd', 'e'};
cout << "Original arrays:" << endl;
Print(a, 5);
Print(b, 5);
Print(c, 5);
cout << "Arrays after GtLever:" << endl;
GtLever(a, 5, 3);
GtLever(b, 5, 3.3);
GtLever(c, 5, 'c');
return 0;
}
template <class T>
void Print(T *p, int n) {
for (int i = 0; i < n; i++) {
cout << p[i] << " ";
}
cout << endl;
}
template <>
void Print<char>(char *p, int n) {
for (int i = 0; i < n; i++) {
cout << p[i];
}
cout << endl;
}
template <class T>
void GtLever(T *p, int n, T lever) {
int j = 0;
for (int i = 0; i < n; i++) {
if (p[i] > lever) {
swap(p[i], p[j]);
j++;
}
}
Print(p, j);
}
```
输出结果:
```
Original arrays:
1 2 3 4 5
1.1 2.2 3.3 4.4 5.5
abcde
Arrays after GtLever:
4 5
4.4 5.5
d e
```