用C++实现,要求用到容器
时间: 2023-07-12 09:04:17 浏览: 37
好的,以下是一个使用C++ STL容器的示例程序:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <map>
int main() {
// 创建一个 vector 容器来存储字符串
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("world");
vec.push_back("!");
// 使用迭代器遍历 vector 容器中的元素
std::cout << "vector:";
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << " " << *it;
}
std::cout << std::endl;
// 创建一个 map 容器来存储键值对
std::map<int, std::string> dict;
dict[1] = "one";
dict[2] = "two";
dict[3] = "three";
// 使用迭代器遍历 map 容器中的元素
std::cout << "map:";
for (auto it = dict.begin(); it != dict.end(); ++it) {
std::cout << " " << it->first << ":" << it->second;
}
std::cout << std::endl;
return 0;
}
```
这个程序定义了一个 vector 容器和一个 map 容器,分别用于存储字符串和键值对。在程序中,我们使用 push_back() 函数向 vector 容器中添加元素,使用 [] 运算符向 map 容器中添加键值对。然后使用迭代器遍历容器中的元素,打印出来。