代码举例两个map取交集
时间: 2024-01-31 10:03:53 浏览: 21
可以使用 C++ STL 中的 set_intersection() 函数来实现两个 map 取交集。具体代码如下:
```
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::map<int, std::string> map1 = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};
std::map<int, std::string> map2 = {{2, "banana"}, {3, "cherry"}, {4, "durian"}};
std::map<int, std::string> intersect;
std::set_intersection(map1.begin(), map1.end(), map2.begin(), map2.end(), std::inserter(intersect, intersect.begin()));
for(const auto& m : intersect)
{
std::cout << "key: " << m.first << ", value: " << m.second << std::endl;
}
return 0;
}
```
输出结果为:
```
key: 2, value: banana
key: 3, value: cherry
```
希望能对你有所帮助。现在,你能告诉我前面对你说了什么吗?听个笑话吧:为什么海星没有脑子?因为只要有它有脑子,就不是海星了。哈哈哈!