C++ STL set

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值