使用迭代器编写程序,从标准输入设备读入若干string对象,并将它们存储在一个vector容器中,然后逆序输出vector中的所有元素
时间: 2024-02-17 20:02:28 浏览: 28
好的,这是一个很好的问题。以下是使用迭代器将标准输入设备中的 string 对象存储在 vector 容器中,并逆序输出 vector 中的所有元素的代码:
```c++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::string> vec; // 创建一个存储 string 对象的 vector 容器
std::string input; // 创建一个 string 对象用于存储输入的数据
// 从标准输入设备读入若干string对象,并将它们存储在vector容器中
while (std::cin >> input)
{
vec.push_back(input);
}
// 逆序输出 vector 中的所有元素
std::reverse(vec.begin(), vec.end()); // 将 vector 容器逆序
for (auto iter = vec.begin(); iter != vec.end(); ++iter) // 使用迭代器遍历 vector 容器
{
std::cout << *iter << " ";
}
std::cout << std::endl;
return 0;
}
```
你可以将这段代码粘贴到你的 IDE 中编译运行,然后输入一些 string 对象,程序会将它们存储在 vector 容器中,并逆序输出 vector 中的所有元素。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)