利用模版和动态分配数组实现对各种数据的输出的例子
时间: 2024-05-01 11:23:28 浏览: 10
以下是一个利用模板和动态分配数组实现对各种数据类型输出的例子:
```c++
#include <iostream>
using namespace std;
template <typename T>
void printArray(T *arr, int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int *intArr = new int[5];
double *doubleArr = new double[5];
char *charArr = new char[5];
for (int i = 0; i < 5; i++) {
intArr[i] = i+1;
doubleArr[i] = (i+1)*1.5;
charArr[i] = 'A'+i;
}
cout << "int array: ";
printArray(intArr, 5);
cout << "double array: ";
printArray(doubleArr, 5);
cout << "char array: ";
printArray(charArr, 5);
delete[] intArr;
delete[] doubleArr;
delete[] charArr;
return 0;
}
```
上述代码定义了一个模板函数`printArray`,该函数可以接受任意类型的数组指针和数组大小,并将数组元素按顺序输出。在`main`函数中,分别定义了一个包含5个元素的整型数组、双精度浮点型数组和字符型数组,并对数组进行初始化。接着,分别调用`printArray`函数输出各个数组的元素。最后,释放动态分配的数组内存。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)