c++ stl set 是一种有序、唯一元素集合容器,它允许插入、删除、查找和判断空等基本操作。它可以存储各种类型的数据,如整数或字符串。例如,要存储整数集合,可以使用 set

C++ 函数的 STL set 怎么用
简介
STL set 是 C++ 标准模板库 (STL) 中的一个容器类,它存储一个唯一的元素集合。set 的特质:
立即学习“C++免费学习笔记(深入)”;
- 有序性: 元素按升序排列。
- 唯一性: 集合中不会出现重复元素。
使用语法
#include <set> using namespace std; set<type> mySet;
其中:
-
type是要存储在 set 中的元素类型。
基本操作
- 插入 (insert): 向 set 中添加一个元素,如果元素已经存在,则不会被添加。
- 删除 (erase): 从 set 中删除一个元素,如果元素不存在,则不会发生任何操作。
- 查找 (find): 搜索 set 中是否有某个元素,如果找到,则返回迭代器;如果未找到,则返回 set::end()。
- 判断空 (empty): 检查 set 是否为空。
- 大小 (size): 返回 set 中元素的数量。
实战案例
存储整数集合
#include <set>
using namespace std;
int main() {
set<int> mySet;
mySet.insert(1);
mySet.insert(3);
mySet.insert(2);
// 输出 set 中的值(因为是 ordered,所以按升序输出)
for (int num : mySet) {
cout << num << " ";
}
// 输出:1 2 3
// 搜索并输出 3
auto it = mySet.find(3);
if (it != mySet.end()) {
cout << "Found 3" << endl;
}
return 0;
}存储字符串集合
#include <set>
#include <string>
using namespace std;
int main() {
set<string> mySet;
mySet.insert("Apple");
mySet.insert("Banana");
mySet.insert("Orange");
// 输出 set 中的值(因为是 ordered,所以按字母顺序输出)
for (const string& fruit : mySet) {
cout << fruit << " ";
}
// 输出:Apple Banana Orange
// 搜索并输出 "Banana"
auto it = mySet.find("Banana");
if (it != mySet.end()) {
cout << "Found Banana" << endl;
}
return 0;
}










