C++ 集合插入和删除

2024 年 8 月 28 日 | 阅读 6 分钟

Set 是 C++ 中内置的一种容器,其概念与数学中描述的集合类似。Set 与其他容器的不同之处在于,它只包含不同的元素,并且这些元素可以按排序顺序遍历。深入理解 set 在竞争性编程和解决算法问题中非常重要。本文将讨论 C++ 中的 set 插入删除

Set 插入

我们可以通过使用 std::set 的两个成员方法将元素插入到 set 容器中:

  1. 使用 insert() 函数
  2. 使用 emplace() 函数

1. 使用 insert() 函数进行插入

语法:1

insert() 方法 用于插入 set 的组件。插入后,元素会重新排序,set 也会排序。此函数可以通过三种不同的方式执行。

此函数向 set 添加一个元素。当传入的元素不在 set 中时,会发生插入。它返回一个 指针对。第一个元素指向已存在或已添加的元素。第二个元素返回布尔结果 “true”“false”

语法:2

在此实现中,指针的指示与要插入的元素一起给出。提示指针帮助 insert() 确定插入应该发生的位置。因此,尝试缩短分配元素所需的时间。提示指针不需要在指定位置插入。此函数返回元素插入的位置作为指针。

语法:3

必须使用此插入类型将其他容器中的元素添加到 set。如果源容器中已找到重复组件,则不添加它们。

示例

我们来看一个例子来演示 C++ 中使用 insert 函数进行 set 插入

输出

Newly inserted element
The elements of the set after the first insertion are 30 
The elements of the set after the second insertion are: 30 34 
The elements of the set after the third insertion are: 25 26 30 34 

2. 使用 emplace() 函数

emplace() 函数 也用于将组件插入到 Set 中。此函数与上面解释的 "insert()" 类似,唯一的区别是元素在元素插入的确切位置 “就地” 构建,而 insert() 则复制已存在的对象。

emplace() 的语法

此方法将 set 的元素总数增加一。它返回一个带有指针对的对象,其中第一个是指向插入元素当前位置的迭代器,第二个是带有布尔值的变量,指示元素是已存在还是新生成。

emplace_hint() 的语法

通过 "hint_iterator" 进行迭代以获取插入点的提示,这可能会减少插入插入元素所需的时间。它不影响插入位置。它发生在其本地定义的位置。

示例

我们来看一个例子来演示 C++ 中使用 emplace() 函数 进行 set 插入

输出

Newly inserted element
The elements of the set after the first insertion are: 25 
The element was inserted already
The elements of the set after the second insertion are: 25 
The elements of the set after the third insertion are: 25 29 

Set 删除

使用 erase() 函数,我们可以从 set 容器中删除元素。它是 std::set 类中的一个函数。它具有以下应用:

语法 1

删除参数中指定的值。删除后,重新排序 set。

语法 2

从其参数中迭代器指示的位置删除值。

语法 3

删除从 "begining_iterator""ending_iterator" 的元素。

示例

我们来看一个例子来演示 C++ 中使用 erase() 函数 进行 set 删除

文件名:Deletion. cpp

输出

The elements of the set after the insertion are: 2 4 6 8 10 12 14 16 18 
The elements of the set after the first deletion are: 6 8 10 12 14 16 18 
The elements of the set after the second deletion are:2 6 8 10 12 14 16 18 
The elements of the set after the third deletion are:2 6 8