主要是想了解下sort的bool operator
【写在结构内的排序规则】
这个是基本结构
bool operator <(const node& as)const
{
return a < as.a;
}
(这里的语义就是重载 ‘<’ 符号, 传入cosnt的被比数 , 然后自己也const)
小于< 代表升序 (1,2,3…)
大于>代表降序 (3,2,1…)
如果要多个判定就:
if (a != as.a)
return a < as.a;
else
return b > as.b;
【写在结构外的排序规则】
基本结构 这个其实我觉得更直观
static bool com(const node& asd, const node& qwe)
{
return asd.a < qwe.a;
}
(多个判定同上)
用的时候直接
sort(s, s + size,com);
就可以了 甚至不需要com()
=
=
=
用vector举例
不加greater升序,加了降序
sort(a.begin(), a.end(), greater<int>());
其中greater要记得写 <>类型 和 () ,这就不像上文com了
当然,自己写规则的话同样可以不加()
static bool com(int& a, int& b)
{ return a > b; }
sort(a.begin(), a.end(), com);
vector装入结构体也是同上文
static bool com(pair<int, int>& a, pair<int, int>& b)
{ return a.first > b.first; }
关于priority_queue
想给特殊结构用它:
1.自定义结构,并且在结构里自定义规则
2.给pair用: priority_queue<pair<>, vector<pair<>>, greater<pair<>>>
;
感觉好麻烦,还不如自定义结构