源代码:

#include <iostream>
#include <set>
using namespace std;

int main(){
	set<string> a_set;
	a_set.emplace("大炮");
	a_set.emplace("大炮");
	a_set.emplace("富贵");
	a_set.emplace("小美");
	a_set.emplace("苹果");
	cout<<"集合的内容是:";
	for(auto& str:a_set){
		cout<<str<<" ";
	}
	a_set.erase("苹果");
	if(a_set.count("苹果")==0){
		cout<<"\n不在集合中"<<endl;
	}
	if(a_set.count("富贵")>0){
		cout<<"在集合中"<<endl;
	}
	return 0;
}

代码详解:

C++ set 容器详解

set 是 C++ 标准模板库(STL)中的一种关联容器,它存储唯一元素并自动排序。下面结合你的代码详细介绍 set 的特性和用法。

基本特性

  1. 唯一性:每个元素在集合中只能出现一次

  2. 自动排序:元素按特定顺序(默认升序)存储

  3. 高效查找:基于红黑树实现,查找时间复杂度 O(log n)

  4. 不可修改元素:元素值不可直接修改(会破坏排序)

你的代码解析

set<string> a_set;
a_set.emplace("大炮");  // 插入第一个"大炮"
a_set.emplace("大炮");  // 重复插入,无效
a_set.emplace("富贵");
a_set.emplace("小美");
a_set.emplace("苹果");

插入操作后集合内容

由于 set 的唯一性和自动排序特性,最终集合内容为(按字符串升序排列):

大炮 富贵 苹果 小美

注意:

  • 第二个"大炮"没有插入成功(唯一性)

  • 元素按字典序自动排序

核心操作详解

1. 插入元素

// 方法1:emplace (C++11推荐)
a_set.emplace("新元素");  // 直接构造,高效

// 方法2:insert
a_set.insert("新元素");   // 插入拷贝

2. 删除元素

// 方法1:通过值删除
a_set.erase("苹果");     // 删除键为"苹果"的元素

// 方法2:通过迭代器删除
auto it = a_set.find("小美");
if (it != a_set.end()) {
    a_set.erase(it);
}

// 方法3:删除范围
a_set.erase(a_set.begin(), next(a_set.begin(), 2)); // 删除前两个元素

3. 查找元素

// 方法1:count (适合检查存在性)
if (a_set.count("富贵") > 0) {
    cout << "元素存在";
}

// 方法2:find (获取迭代器)
auto pos = a_set.find("大炮");
if (pos != a_set.end()) {
    cout << "找到:" << *pos;
}

// 方法3:contains (C++20)
if (a_set.contains("苹果")) {
    cout << "包含苹果";
}

4. 遍历集合

// 方法1:范围for循环 (推荐)
for (const auto& elem : a_set) {
    cout << elem << " ";
}

// 方法2:使用迭代器
for (auto it = a_set.begin(); it != a_set.end(); ++it) {
    cout << *it << " ";
}

重要成员函数

函数 描述 时间复杂度
insert(value) 插入元素 O(log n)
emplace(args...) 直接构造元素 O(log n)
erase(key) 删除元素 O(log n)
find(key) 查找元素,返回迭代器 O(log n)
count(key) 统计元素出现次数(0或1) O(log n)
size() 返回元素数量 O(1)
empty() 检查是否为空 O(1)
clear() 清空集合 O(n)
lower_bound(key) 返回第一个不小于key的元素 O(log n)
upper_bound(key) 返回第一个大于key的元素 O(log n)
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐