#include <iostream>
#include <set>
using namespace std;
int main() {
// 创建一个 set 容器,存储 int 类型的元素
set<int> s;
// 插入元素到 set 中
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(20); // 重复插入,不会改变 set
// 输出 set 中的元素
cout << "Set elements: ";
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 检查某个元素是否在 set 中
if (s.find(20) != s.end()) {
cout << "Element 20 is in the set." << endl;
} else {
cout << "Element 20 is not in the set." << endl;
}
// 删除 set 中的一个元素
s.erase(20);
// 再次输出 set 中的元素
cout << "Set elements after removing 20: ";
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
创建 set 容器:set<int> s;
创建了一个存储 int
类型元素的 set
容器。set
是 C++ STL 中的一种关联容器,它会自动对插入的元素进行排序,并且不允许重复元素。
插入元素:使用 insert()
方法向 set
中插入元素。由于 set
不允许重复元素,所以插入相同的元素多次也不会改变 set
的内容。
遍历 set:通过迭代器遍历 set
中的所有元素,并输出它们。set
中的元素是按升序排列的。
查找元素:使用 find()
方法检查某个元素是否存在于 set
中。如果找到了该元素,则返回指向该元素的迭代器;否则返回 end()
。
删除元素:使用 erase()
方法从 set
中删除指定的元素。
再次遍历:删除元素后,再次遍历并输出 set
中的元素,以验证删除操作的效果。
希望这段代码和解释能帮助你理解 C++ 中 set
的基本用法。
上一篇:c++ 字符串转int
下一篇:c++中const
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站