1、在vector容器中的排序
直接使用sort()算法,所需头文件为 #include< algorithm >,
如果元素为数字,默认为升序,可以自定义比较函数来控制元素的排序规则。
默认:
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(3);
v.push_back(5);
v.push_back(9);
v.push_back(1);
sort(v.begin(),v.end());
for(vector<int>::iterator it = v.begin();it!=v.end();it++)
cout<<*it<<" ";
return 0;
}
自定义排序规则:
当vector中的元素为结构体时,可以自定义函数对结构体的排序规则自行定义。在这里我们还是以int型变量为例子。
#include<bits/stdc++.h>
using namespace std;
// 自定义比较方式
bool cmp(const int &a,const int &b)
{
return a>=b;
}
int main()
{
vector<int> v;
v.push_back(3);
v.push_back(5);
v.push_back(9);
v.push_back(1);
sort(v.begin(),v.end(),cmp);
for(vector<int>::iterator it = v.begin();it!=v.end();it++)
cout<<*it<<" ";
return 0;
}
2、集合Set中排序
STL中的set使用了红黑二叉树结构,根节点的值大于等于左子树的值小于右子树的值。因此元素之间必须可以进行比较。
自定义比较结构体,重载运算符“()”:
#include<bits/stdc++.h>
using namespace std;
// 在结构体中重载()运算符
struct mycmp{
bool operator () (const int &a,const int &b)
{
return a>=b;
}
};
int main()
{
set<int,mycmp> s;
s.insert(3);
s.insert(5);
s.insert(9);
s.insert(1);
for(set<int,mycmp>::iterator it = s.begin();it!=s.end();it++)
cout<<*it<<" ";
return 0;
}
在结构体中直接定义比较函数:
#include<bits/stdc++.h>
using namespace std;
struct Stu
{
int score;
string name;
//在结构体中定义比较函数
bool operator <(const Stu &a) const{
return a.score<score;
}
};
int main()
{
set<Stu> s;
Stu t;
t.score = 90;
s.insert(t);
t.score = 100;
s.insert(t);
t.score = 80;
s.insert(t);
for(set<Stu>::iterator it = s.begin();it!=s.end();it++)
cout<<(*it).score<<" ";
return 0;
}