set是关联式容器。在set中每个元素的值都唯一(multiset中一个值可以出现多次),而且系统能根据元素的值自动进行排序,所以不能指定插入位置。应该注意的是set中数元素的值不能直接被改变(不能使用at()和[ ]操作符),如果希望修改一个元素的值,必须先删除原有的元素,再插入新的元素。C++ STL中标准关联容器set, multiset, map, multimap内部采用的就是一种非常高效的平衡检索二叉树:红黑树
#define _CRT_SECURE_NO_WARNINGS
#include <set>
#include <iostream>
using namespace std;
class Student
{
public:
Student(char* name, int age)
{
strcpy(this->name, name);
this->age = age;
}
public:
char name[64];
int age;
};
//仿函数
struct FunStudent
{
bool operator()(const Student &stu1, const Student &stu2)
{
if (stu1.age < stu2.age)
{
return true;
}
else
{
return false;
}
}
};
void main()
{
set<int> set1;//默认是从小到大排序,相当于set<int,less<int>>
set<int, greater<int>> set2;//从大到小
for (int i = 0; i < 5; i++)
{
set1.insert(i + 1);
}
set1.insert(-1);
set1.insert(150);
set1.insert(100);//set会自动排序
set1.insert(100);//set元素具有唯一性,此项不会被插入
for (set<int>::iterator it=set1.begin();it!=set1.end();it++)
{
cout << *it << " ";
}
cout << endl;
//自定义数据类型的比较,需要用到仿函数
set<Student,FunStudent> set3;
Student s1((char*)"s1",38);
Student s2((char*)"s2", 25);
Student s3((char*)"s3", 30);
Student s4((char*)"s4", 18);
Student s5((char*)"s5", 18);
set3.insert(s1);
set3.insert(s2);
set3.insert(s3);
set3.insert(s4);
//insert函数的返回值为pair<iterator, bool>,是一个迭代器以及布尔对,可以通过布尔值判断是否插入成功
pair<set<Student,FunStudent>::iterator, bool> pair1 = set3.insert(s5);//年龄相同,此条数据不会被插入成功
if (pair1.second)
{
cout << "添加成功!" << endl;
}
else
{
cout << "添加失败" << endl;
}
for (set<Student,FunStudent>::iterator it=set3.begin();it!=set3.end();it++)
{
cout << it->name << " " << it->age << endl;
}
set<int> set4;
for (int i = 0; i < 10; i++)
{
set4.insert(i + 1);
}
for (set<int>::iterator it=set4.begin();it!=set4.end();it++)
{
cout << *it << " ";
}
cout << endl;
//查找元素5的位置
set<int>::iterator it1 = set4.find(5);
cout << "元素5的位置:" << *it1 << endl;
//元素5的个数,只能是0或1
int num = set4.count(5);
cout << "元素5的个数:" << num << endl;
//大于等于5
set<int>::iterator it2 = set4.lower_bound(5);
cout << "大于等于5的元素位置:" << *it2 << endl;
//大于5
set<int>::iterator it3 = set4.upper_bound(5);
cout << "大于5的元素位置:" << *it3 << endl;
//equal_range返回一个pair,包含两个迭代器,第一个为大于等于5,第二个为大于5
pair<set<int>::iterator, set<int>::iterator> myPair = set4.equal_range(5);
set<int>::iterator it4 = myPair.first;
set<int>::iterator it5 = myPair.second;
cout << "it4:" << *it4 << endl;
cout << "it5:" << *it5 << endl;
//删除元素5
set4.erase(5);
system("pause");
}
运行结果:
更多内容见:https://blog.youkuaiyun.com/changjiale110/article/details/79108447