使用set时,需包含头文件< set>
set具备的两个特点:
set中的元素都是排序好的
set中的元素都是唯一的,没有重复的
.
一、定义及初始化
// 列表初始化
set <int> num = { 1, 2, 3 };
// 相同常量会自动去除
set <int> num = { 1, 2, 3, 1 }; // num = { 1, 2, 3 }
二、插入元素
// 插入一个元素
num.insert(4);
// 插入一个元素列表
num.insert({ 4, 5, 6 })
// 插入另一个容器中的一段元素
set <int> num1 = { 1, 2, 3 };
set <int> num2 = { 4, 5, 6 };
num1.insert(num2.begin(), num2.end());
三、删除元素
// 删除一个元素
set <int> num= { 1, 2, 3 };
num.erase(1);
// 通过迭代器删除一个元素
set <int> num= { 1, 2, 3 };
num.erase(num.begin());
// 删除一个由迭代器指定的范围
set <int> num= { 1, 2, 3 };
num.erase(num.begin(), num.begin()+2);
四、寻找元素
set <int> num= { 1, 2, 3 };
// find() 返回一个指向被查找到元素的迭代器
auto it = num.find(1); //i t = num.begin()
// 带查找的元素不在 set 对象中,则返回其尾后迭代器 end()
auto it = num.find(4); // it = num.end()
// lower_bound() 返回第一个大于或等于 k 的元素的迭代器
auto it = num.lower_bound(2); // *it = 2;
// upper_bound() 返回第一个大于 k 的元素的迭代器
auto it = num.upper_bound(2); // *it = 3;
五、遍历元素
//遍历数据,用迭代器遍历数据
set <int> num= { 1, 2, 3 };
for (set <int>::iterator it = num.begin(); it != num.end(); it++)
{
cout << *it << endl;
}
六、交换元素
set <int> num1 = { 1, 2, 3 };
set <int> num2 = { 4, 5, 6 };
num1.swap(num2);
七、获取元素个数
set <int> num= { 1, 2, 3 };
int size = num.size();
八、排序
set自动进行排序,也是从小到大,所以不能使用sort进行排序