// 集合交运算 Set intersection(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { if (strstr(set2.head, &(p->data)) != NULL) { insert(&set, p->data); } p = p->next; } return set; } // 集合并运算 Set union_set(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { insert(&set, p->data); p = p->next; } p = set2.head; while (p != NULL) { if (strstr(set.head, &(p->data)) == NULL) { insert(&set, p->data); } p = p->next; } return set; } // 集合差运算 Set difference(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { if (strstr(set2.head, &(p->data)) == NULL) { insert(&set, p->data); } p = p->next; } return set; }
时间: 2024-03-11 13:44:26 浏览: 26
这段代码实现了集合的交、并、差等运算。其中交运算(intersection)遍历集合1中的所有元素,如果该元素也在集合2中则将其加入到新集合中。并运算(union_set)先将集合1中的所有元素加入到新集合中,再遍历集合2中的所有元素,如果该元素不在新集合中则将其加入到新集合中。差运算(difference)遍历集合1中的所有元素,如果该元素不在集合2中则将其加入到新集合中。这些运算都使用了集合的初始化、插入元素等基本操作来构造新的集合。需要注意的是在判断字符在集合中是否存在时使用了 strstr 函数,该函数常用于判断字符串中是否包含指定字符串。在这里可以用来判断字符是否在集合中。
相关问题
python里set集合运算
在 Python 中,set(集合)是一个无序的、不重复的元素集合,可以进行以下的集合运算:
1. 并集(Union):将两个集合中所有的元素合并成一个集合。
```
a = {1, 2, 3}
b = {2, 3, 4}
c = a | b # 或者使用 c = a.union(b)
print(c) # 输出 {1, 2, 3, 4}
```
2. 交集(Intersection):获取两个集合中共有的元素。
```
a = {1, 2, 3}
b = {2, 3, 4}
c = a & b # 或者使用 c = a.intersection(b)
print(c) # 输出 {2, 3}
```
3. 差集(Difference):获取属于集合 A 而不属于集合 B 的元素。
```
a = {1, 2, 3}
b = {2, 3, 4}
c = a - b # 或者使用 c = a.difference(b)
print(c) # 输出 {1}
```
4. 对称差集(Symmetric Difference):获取属于集合 A 或属于集合 B,但不同时属于两个集合的元素。
```
a = {1, 2, 3}
b = {2, 3, 4}
c = a ^ b # 或者使用 c = a.symmetric_difference(b)
print(c) # 输出 {1, 4}
```
此外,Python 中还有其他的集合运算,例如子集(Subset)、超集(Superset)等,可以通过 set 类型的方法进行计算。
set_intersection
set_intersection 是C++中的一个函数,用于计算两个有序集合的交集(即共有的元素)。这个函数需要两个有序集合作为输入,并将结果存储在另一个集合中。
在C++中,使用 set_intersection 函数的一般语法如下:
```cpp
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first);
```
其中,first1 和 last1 分别是第一个有序集合的起始迭代器和终止迭代器;first2 和 last2 是第二个有序集合的起始迭代器和终止迭代器;d_first 是输出迭代器,用于存储交集。
这个函数会将两个有序集合的交集元素复制到输出迭代器所指向的位置,并返回指向输出范围末尾的迭代器。
以下是使用 set_intersection 函数的一个示例:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> set1 = {1, 2, 3, 4, 5};
std::vector<int> set2 = {4, 5, 6, 7, 8};
std::vector<int> intersection;
std::set_intersection(set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::back_inserter(intersection));
std::cout << "Intersection: ";
for (const auto& num : intersection) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
运行结果将输出:
```
Intersection: 4 5
```
这表示两个集合的交集是 {4, 5}。