欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原创 linux下c++ lesson24 容器set

程序员文章站 2022-05-31 16:14:38
...

1-set的使用.cpp

#include <iostream>
#include <set>

using namespace std;

class Student
{
private:	
	int id;
	string name;
public:
	Student(int i, string n);
	void show()const;
	bool operator<(const Student &s) const;
	bool operator>(const Student &s) const;
};

Student::Student(int i, string n)
{
	id = i;
	name = n;
}

void Student::show() const
{
	cout << "id " << id << "    name " << name << endl; 
}

bool Student::operator<(const Student &s) const
{
	return this->id < s.id;
}

bool Student::operator>(const Student &s) const
{
	return this->id > s.id;
}

int main()
{
	Student s1(3, "aa");
	Student s2(1, "zz");
	Student s3(5, "ff");
	Student s4(4, "ee");
	Student s5(2, "bb");
	Student s6(7, "cc");
	Student s7(8, "hh");
	Student s8(6, "jj");

	//set<Student> s;
	set<Student, greater<Student> > s;

	s.insert(s1);
	s.insert(s2);
	s.insert(s3);
	s.insert(s4);
	s.insert(s5);
	s.insert(s6);
	s.insert(s7);
	s.insert(s8);

	for (set<Student>::iterator it = s.begin(); it != s.end(); it++)
	{
		it->show();
	}

	cout << "集合大小:" << s.size() << endl;

	cout << "set的删除" << endl;
	s.erase(s.begin());
	for (set<Student>::iterator it = s.begin(); it != s.end(); it++)
	{
		it->show();
	}

	cout << "set区间删除" << endl;
	s.erase(--(s.end()), s.end());
	for (set<Student>::iterator it = s.begin(); it != s.end(); it++)
	{
		it->show();
	}
	
	cout << "set删除具体元素" << endl;
	Student stu(3, "zz");    //按照id查找并删除
	s.erase(stu);
	for (set<Student>::iterator it = s.begin(); it != s.end(); it++)
	{
		it->show();
	}

	cout << "set的查找" << endl;
	//set<Student, greater<Student> >::iterator it = s.find(stu);
	set<Student, greater<Student> >::iterator it = s.find(s6);
	if (it == s.end())
	{
		cout << "对象不存在" << endl;
	}
	else
	{
		it->show();
	}

	cout << "set的统计" << endl;
	cout << s.count(s6) << endl;

	cout << "lower_bound" << endl;
	Student ss(3, "aaa");
	it = s.lower_bound(ss);
	if (it == s.end())
	{
		cout << "不存在" << endl;
	}
	else
	{
		it->show();
	}

	cout << "upper_bound" << endl;
	it = s.upper_bound(s6);
	if (it == s.end())
	{
		cout << "不存在" << endl;
	}
	else
	{
		it->show();
	}

	cout << "equal_range" << endl;
	//pair 类型 模板类 有两个成员变量
	pair<set<Student, greater<Student> >::iterator, set<Student, greater<Student> >::iterator> p;    //创建pair对象
	p = s.equal_range(ss);
	p.first->show();      //p.first第一个类型(迭代器)
	p.second->show();     //p.second第二个类型(迭代器)

	return 0;
}
	

相关标签: Linux c++