使用vector和list容器实现正向输出所有元素的函数
时间: 2024-03-24 21:36:47 浏览: 22
使用vector容器实现:
```c++
#include <iostream>
#include <vector>
void printAllElements(const std::vector<int>& vec) {
for (const auto& elem : vec) {
std::cout << elem << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
printAllElements(vec);
return 0;
}
```
使用list容器实现:
```c++
#include <iostream>
#include <list>
void printAllElements(const std::list<int>& lst) {
for (const auto& elem : lst) {
std::cout << elem << " ";
}
std::cout << std::endl;
}
int main() {
std::list<int> lst{1, 2, 3, 4, 5};
printAllElements(lst);
return 0;
}
```
以上两个函数均接收一个引用参数,分别是vector和list容器的引用。函数体内使用range-based for循环遍历容器内的所有元素,并输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)