怎么用set

时间:2025-01-17 21:30:19 游戏攻略

使用 `set` 编写程序主要涉及以下步骤和概念:

定义和初始化

在C++中,可以使用 `set` 来定义一个存储 `int` 类型元素的集合。例如:

```cpp

include

include

using namespace std;

int main() {

set mySet;

mySet.insert(10);

mySet.insert(5);

mySet.insert(20);

for (int val : mySet) {

cout << val << " ";

}

cout << endl;

}

```

插入元素

使用 `insert()` 方法向集合中添加元素。例如:

```cpp

mySet.insert(30);

```

遍历输出

使用范围循环(range-based for loop)遍历并输出集合中的元素。例如:

```cpp

for (int val : mySet) {

cout << val << " ";

}

```

自动排序

`set` 默认按升序排列元素。如果需要自定义顺序,可以使用 `std::greater`。例如:

```cpp

include

include

using namespace std;

int main() {

set> mySet;

mySet.insert(10);

mySet.insert(5);

mySet.insert(20);

for (int val : mySet) {

cout << val << " ";

}

cout << endl;

}

```

集合操作

`set` 支持常见的集合操作,如并集、交集和差集。例如:

```cpp

include

include

include

using namespace std;

int main() {

set set1 = {1, 2, 3, 4, 5};

set set2 = {4, 5, 6, 7, 8};

set unionSet = set1 | set2;

set intersectionSet = set1 & set2;

set differenceSet = set1 - set2;

cout << "Union: ";

for (int val : unionSet) {

cout << val << " ";

}

cout << endl;

cout << "Intersection: ";

for (int val : intersectionSet) {

cout << val << " ";

}

cout << endl;

cout << "Difference: ";

for (int val : differenceSet) {

cout << val << " ";

}

cout << endl;

}

```

其他操作

`set` 还支持其他一些有用的方法,如 `add()` 用于向集合中添加元素,`remove()` 用于从集合中删除元素,以及 `update()` 用于将一个集合的所有元素添加到另一个集合中。例如:

```cpp

mySet.add(60);

mySet.remove(10);

mySet.update(set2);

```

通过以上步骤和示例,你可以使用 `set` 编写各种程序,实现元素的存储、插入、遍历和集合操作等功能。