std::set交集
时间: 2023-10-23 19:08:50 浏览: 115
std::set没有内置的交集操作。但是可以通过迭代器遍历两个set,并找出共同的元素来实现交集操作。下面是一个示例代码,演示了如何找到两个std::set的交集元素:
```cpp
#include <iostream>
#include <set>
int main() {
std::set<int> set1 = {1, 2, 3, 4, 5};
std::set<int> set2 = {4, 5, 6, 7, 8};
std::set<int> intersection;
for (auto it = set1.begin(); it != set1.end(); ++it) {
if (set2.find(*it) != set2.end()) {
intersection.insert(*it);
}
}
std::cout << "Intersection of set1 and set2: ";
for (auto it = intersection.begin(); it != intersection.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
```
这段代码首先创建了两个std::set对象set1和set2,然后通过遍历set1中的元素,并在set2中查找是否存在相同的元素。如果存在,将该元素插入到intersection set中。最后,遍历intersection set并打印出交集的元素。可以输出:Intersection of set1 and set2: 4 5 。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C++ STL set和multiset的使用交集并集差集算法](https://blog.csdn.net/lishenglong666/article/details/44195041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文