set的用法
参考链接:https://www.cnblogs.com/caiyishuai/p/8646345.html
#include<set>
#include<iostream>
using namespace std;
int main()
{
set<int>s;
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
s.insert (x);
}
set<int>::iterator it;
for(it=s.begin ();it!=s.end ();it++)
{
printf("%d\n",*it);
}
//s.end()没有值
cout<<"s.begain() "<<*s.begin ()<<endl;
//lower_bound()--返回指向大于(或等于)某值的第一个元素的迭代器
cout<<"lower_buond 3 "<<*s.lower_bound (3)<<endl;
//upper_bound()--返回大于某个值元素的迭代器
cout<<"upper_bound 3 "<<*s.upper_bound (3)<<endl;
//find()--返回一个指向被查找到元素的迭代器
cout<<"find() 3 "<<*s.find(3)<<endl;
cout<<"s.size() "<<s.size ()<<endl;
return 0;
}
常用判断是否包含一个元素。
#include <iostream>
#include <set>
using namespace std;
int main()
{
int a[] = {1,2,3};
set<int> s(a,a+3);
set<int>::iterator iter;
if((iter = s.find(2)) != s.end())
{
cout<<*iter<<endl;//输出为2
}
return 0;
}
- set中存储对象
#include <stdio.h>
#include<string.h>
#include<iostream>
#include<set>
using namespace std;
class Student
{
public:
Student( char *name, int age)
{
int len=strlen(name)+1;
this->name=new char[len];
strcpy(this->name, name);
this->age = age;
}
//set中是只用<判断值的大小,所以只能重载小于号,同理小根堆也是一样的
bool operator<(const Student& ps)const{
if(this->age>ps.age)
return true;
else
return false;
}
~Student(){
//不能析构,因为作用域消失后会自动析构导致无法打印
// delete[] name;
}
public:
char *name;
int age ;
};
int main()
{
set<Student> set1;
Student s1("张1", 32);
set1.insert(s1);
set1.insert(Student("张2", 32) );
set1.insert(Student("张3", 53) );
set1.insert(Student("张4", 34) );
//打印输出
for (set<Student >::iterator it = set1.begin(); it != set1.end(); it++)
{
cout<< (*it).name << " ";
}
return 0;
}
- set中默认重小到大
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);
//打印输出
for (set<int>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout<< *it << " ";
}
cout << endl;
//删除集合
cout << "\n删除集合";
while (!set1.empty())
{
set<int>::iterator it = set1.begin();
printf("%d ", *it);
set1.erase(set1.begin());
}
- set中小到大,大到小
set<int, greater<int>> set1;
for (int i=0; i<5; i++)
{
int tmp = rand();
set1.insert(tmp);
}
set1.insert(100);
set1.insert(100);
set1.insert(100);
//打印输出
for (set<int, greater<int>>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout<< *it << " ";
}
cout << endl;
//删除集合
cout << "\n删除集合";
while (!set1.empty())
{
set<int, greater<int>>::iterator it = set1.begin();
printf("%d ", *it);
set1.erase(set1.begin());
}