C++ map存储set类型
时间: 2024-01-23 08:02:55 浏览: 37
在 C++ 中,可以使用 STL 的 map 容器来存储 set 类型。具体来说,map 的 key 为 set 的元素类型,value 为 set,这样就可以将多个 set 存储在一个 map 中,并且可以通过 map 的 key 来访问对应的 set。以下是一个示例:
```c++
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main() {
map<int, set<string>> dict;
dict[1].insert("apple");
dict[1].insert("banana");
dict[2].insert("orange");
dict[2].insert("grape");
cout << "Set 1 contains " << dict[1].size() << " elements:" << endl;
for (auto it = dict[1].begin(); it != dict[1].end(); ++it) {
cout << *it << endl;
}
cout << "Set 2 contains " << dict[2].size() << " elements:" << endl;
for (auto it = dict[2].begin(); it != dict[2].end(); ++it) {
cout << *it << endl;
}
return 0;
}
```
以上代码中,我们定义了一个 map,key 为 int 类型,value 为 set<string> 类型。通过 dict[1] 和 dict[2] 分别访问了两个 set,并输出了它们的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)