C++ set集合模型操练
set是一个集合容器,其中所包含的元素是唯一的,集合中的元素按一定顺序排列
元素插入过程是按排序规则插入,故不可指定位置插入
set采用红黑树变体的数据结构实现,红黑树属于平衡二叉树。在插入删除操作上比vector快
set不能直接存取元素(即,不可使用[]和*.at())
multiset与set的区别:set支持唯一键值,每个元素只出现一次;multiset同一值可出现多次
不可直接修改set和multiset中的元素值,因为该容器是自动排序的。要想修改一个元素,必须先删除它,再插入新的元素
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <set>
using namespace std;
/*
set是一个集合容器,其中所包含的元素是唯一的,集合中的元素按一定顺序排列
元素插入过程是按排序规则插入,故不可指定位置插入
set采用红黑树变体的数据结构实现,红黑树属于平衡二叉树。在插入删除操作上比vector快
set不能直接存取元素(即,不可使用[]和*.at())
multiset与set的区别:set支持唯一键值,每个元素只出现一次;multiset同一值可出现多次
不可直接修改set和multiset中的元素值,因为该容器是自动排序的。要想修改一个元素,必须先删除它,再插入新的元素
*/
class Student
{
public:
Student(string name, int age)
{
this->name = name;
this->age = age;
}
public:
string name;
int age;
};
struct FuncStudent
{
bool operator()(const Student& left, const Student& right)
{
return (left.age < right.age);
}
};
int main()
{
//1 基本数据类型
set<int> set1;//相当于 set<int, less<int>> set1//默认从小到大
for (int i = 0; i < 5; i++)
{
int tmp = rand();
set1.insert(tmp);
}
set1.insert(5);
set1.insert(100);
set1.insert(100);
for (set<int>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//5 100 6334 11478 15724 18467 19169
//删除集合
while (!set1.empty())
{
set<int>::iterator it = set1.begin();
cout << *it << " ";
set1.erase(it);
}
cout << endl << endl;
set<int, greater<int>> set2;
for (int i = 0; i < 5; i++)
{
int tmp = rand();
set2.insert(tmp);
}
//从大到小排序
for (set<int, greater<int>>::iterator it = set2.begin(); it != set2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//2 自定义数据类型的比较 ===>仿函数 函数对象
Student s1("s1", 31);
Student s2("s2", 32);
Student s3("s3", 22);
Student s4("s4", 44);
set<Student, FuncStudent> setS1;
setS1.insert(s1);
setS1.insert(s2);
setS1.insert(s3);
setS1.insert(s4);
//遍历
for (set<Student, FuncStudent>::iterator it = setS1.begin(); it != setS1.end(); it++)
{
cout << it->age << "\t" << it->name << endl;
}
set<int> set3;
for (int i = 0; i < 10; i++)
{
set3.insert(i+1);
}
set<int>::iterator it0 = set3.find(5);
cout << "*it0: " << *it0 << endl;
int num1 = set3.count(5);
cout << "num1: " << num1 << endl;
set<int>::iterator it1 = set3.lower_bound(5);
cout << "*it1: " << *it1 << endl;
set<int>::iterator it2 = set3.lower_bound(5);
cout << "*it2: " << *it2 << endl;
//set3.erase(5);
pair<set<int>::iterator, set<int>::iterator> myPair = set3.equal_range(5);
set<int>::iterator it3 = myPair.first;
cout << "*it3: " << *it3 << endl;//5 //6
set<int>::iterator it4 = myPair.second;
cout << "*it4: " << *it4 << endl;//6 //6
return 0;
}
本文深入探讨了C++中set和multiset容器的特性与应用,包括数据结构实现、元素插入规则、唯一性和重复性的区别,以及如何进行自定义数据类型比较。通过实例演示了如何使用set和multiset,涵盖了随机数插入、删除操作、自定义比较函数对象、查找元素等关键操作。
654

被折叠的 条评论
为什么被折叠?



