定义一个函数输出vector中的元素
时间: 2024-03-05 22:55:17 浏览: 18
可以定义一个函数,使用模板实现输出 vector 中的元素,代码如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void printVector(const vector<T>& vec)
{
for (auto x : vec)
{
cout << x << " ";
}
cout << endl;
}
int main()
{
vector<int> vec1 = {1, 2, 3, 4, 5};
vector<double> vec2 = {1.1, 2.2, 3.3, 4.4, 5.5};
vector<string> vec3 = {"hello", "world", "!"};
printVector(vec1);
printVector(vec2);
printVector(vec3);
return 0;
}
```
上述代码中,定义了一个模板函数 `printVector`,该函数使用了一个模板参数类型 `typename T`,并接收一个 vector 类型的常量引用参数 `const vector<T>& vec`,然后使用 for-each 循环语法遍历 vector 中的元素,输出每个元素的值。在主函数中,分别创建了三个不同类型的 vector,并通过调用 `printVector` 函数输出了这三个 vector 中的元素。