#include<iostream>
#include"algorithm"
#include"string"
#include<set>
using namespace std;
void myprintf(set<int> &set1);
//集合,元素唯一 不能按照[]方式插入元素 自动排序默认从小到大
//红黑树
void myfun()
{
set<int> set1;
for (int i = 0; i < 5; i++)
{
int tmp = rand();
set1.insert(tmp);
}
//插入重复元素,只出现一个,因为是集合
set1.insert(100);
set1.insert(100);
set1.insert(100);
myprintf(set1);
cout << endl;
//删除集合中的元素
set<int>::iterator it = set1.begin();
while (set1.size() > 0)
{
it = set1.begin();
set1.erase(*it);
myprintf(set1);
cout << endl;
}
}
void myprintf(set<int> &set1)
{
if (set1.size() == 0) cout << "empty" << endl;
for (set<int>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout << *it << " ";
}
}
//对基本的数据类型set能自动排序
void myfun2()
{
set<int> set1;
set<int, less<int>> set2;
//set<int, greater<int>> set3;//从大到小 不能用 报错 why???
for (int i = 0; i < 5; i++)
{
int tmp = rand();
set1.insert(tmp);
}
}
// 对复杂的数据类型 Teacher Student
class Student
{
public:
Student(char *name,int age)
{
strcpy_s(this->name, name);
this->age = age;
}
public:
char name[64];
int age;
};
//仿函数
struct FunStudent
{
bool operator()(const Student &left, const Student &right)
{
if (left.age < right.age) return true;//从小到大 按照年龄排序
else return false;
}
};
void main93()
{
Student s1("a1", 33);
Student s2("b2", 23);
Student s3("c3", 43);
Student s4("d4", 22);
Student s5("d5", 22);//如果两个22岁,能插入成功吗?of course not
set<Student,FunStudent> set1;
set1.insert(s1);
set1.insert(s2);
set1.insert(s3);
/* set1.insert(s4);
set1.insert(s5);*/
//如何知道插入的结果
// _Pairib insert(const value_type& _Val)
// typedef pair<iterator, bool> _Pairib;
//如何知道set1.insert的返回值
pair<set<Student, FunStudent>::iterator, bool> p1 = set1.insert(s4);
pair<set<Student, FunStudent>::iterator, bool> p2 = set1.insert(s5);
//怎么用这个返回值?
if (p1.second == true)cout << "insert s4 ok" << endl;
else cout << " insert s4 no" << endl;
if (p2.second == true)cout << "insert s5 ok" << endl;
else cout << " insert s5 no" << endl;
for (set<Student, FunStudent>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout << it->age << "\t"<<it->name<<endl;
}
}
void main95()
{
set<int> set1;
for (int i = 0; i < 10; i++)
{
set1.insert(i+1);
}
for (set<int>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//搜索5所在的迭代器的位置
set<int>::iterator it2 = set1.find(5);
cout << *it2 << endl;
//count 5 的个数
cout << set1.count(5) << endl;
//删除3元素
set1.erase(3);
set<int>::iterator it3, it4;
it3 = set1.lower_bound(3);// >=3的迭代器的位置
cout << *it3 << endl;
it4 = set1.upper_bound(3);// >3的迭代器的位置
cout << *it4 << endl;
pair<set<int>::iterator, set<int>::iterator> p1=set1.equal_range(3);
set<int>::iterator t3 = p1.first;
set<int>::iterator t4 = p1.second;
cout << " [first,second)=[" << *t3 << ", " << *it4 << ")" << endl;
}
C++学习笔记-set容器
猜你喜欢
转载自blog.csdn.net/m0_37393277/article/details/68936821
今日推荐
周排行