C++中set是自动排序且元素唯一的关联容器,需包含<set>头文件;通过insert插入、erase删除、find查找元素,支持范围for循环遍历,默认升序可改为降序或自定义比较,常用函数包括size、empty、clear及lower_bound/upper_bound,适用于去重与有序存储场景。

在C++中,set 是一个非常实用的关联式容器,属于STL(标准模板库)的一部分。它能自动对存储的元素进行排序,并保证元素的唯一性。下面详细介绍 set 的基本用法和常见操作,帮助你快速掌握它的使用方法。
使用 set 需要包含头文件 <set>,然后根据需要定义数据类型:
#include <set>
#include <iostream>
using namespace std;
int main() {
set<int> s; // 存储整数的set
set<string> names; // 存储字符串的set
return 0;
}
set 提供了简洁的成员函数来管理数据:
s.insert(10);
s.insert(5);
s.insert(10); // 重复,不会插入
if (s.find(5) != s.end()) {
cout << "5 exists in the set\n";
}
s.erase(10);
cout << "Size: " << s.size() << endl; // 输出 1
set 中的元素默认按升序排列,可用范围 for 循环或迭代器遍历:
立即学习“C++免费学习笔记(深入)”;
for (const auto& elem : s) {
cout << elem << " ";
}
// 输出:5
// 或使用迭代器
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
默认情况下,set 按 less 排序(升序)。可以通过传入比较函数改变顺序,例如实现降序:
set<int, greater<int>> descSet;
descSet.insert(3);
descSet.insert(1);
descSet.insert(4);
for (int x : descSet) {
cout << x << " ";
}
// 输出:4 3 1
也可以自定义结构体或类的比较逻辑,只需提供仿函数或 lambda(需用指针或包装)。
if (!s.empty()) {
cout << "Min element: " << *s.begin() << endl;
cout << "Max element: " << *s.rbegin() << endl;
}
基本上就这些。set 适合用于去重、有序存储和快速查找的场景,虽然插入和删除时间复杂度为 O(log n),但使用起来非常方便。掌握这些基础操作后,你可以灵活运用于算法题或实际项目中。
以上就是c++++中set数据结构怎么用_c++ set容器使用方法指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号