zoukankan      html  css  js  c++  java
  • 自定义结构或类的比较

    存放在数组或vector中的排序:

    定义普通函数:

     1 #include <iostream>
     2 #include <algorithm>
     3 using namespace std;
     4 struct act{
     5     int num;
     6     int s;
     7     int e;
     8 };
     9 bool lessact(const act& a1,const act &a2){
    10     return a1.e<a2.e;
    11 }
    12 int main() {
    13 
    14     act *all=new act[n];
    15 
    16     sort(all.begin(),all.end(),lessact);
    17 
    18 }

    定义成员函数:

    在函数内部定义<或者>,再在排序时候使用less<>(),或者greater<>()。

    如果是greater,要注意头文件:#include <functional>

     1 #include<iostream>
     2 #include<algorithm>
     3 #include <functional>
     4 using namespace std;
     5 
     6 struct Thing
     7 {
     8     int v;//单价
     9     int w;//重量
    10     bool operator<(const Thing& other)const{
    11         return v < other.v;
    12     }
    13     bool operator>(const Thing& other)const{
    14         return v > other.v;
    15     }
    16 };
    17 
    18 ...
    19     sort(t, t + n, greater<Thing>());
    20 
    21 ...

    如果是存放在vector中,甚至可以直接比较两个vector:v1>v2

    如果是用在set或者map中,则可以定义单独的struct或类,也可以是成员函数

    class SymbolLess : public std::binary_function<Symbol, Symbol, bool>{
    public:  
        bool operator () (Symbol* lhs, Symbol* rhs) const  
        {  
            return lhs->getContent()< rhs->getContent();  
        }  
    };  
    
    ...
    set<Symbol*, SymbolLess> Symbols;//使用
    ...
  • 相关阅读:
    【CQOI2015】网络吞吐量
    【SDOI2010】所驼门王的宝藏
    【NOIP2013】华容道
    【SNOI2019】通信
    【IOI2016】railroad
    【AtCoder3611】Tree MST
    【AtCoder2134】ZigZag MST
    【CF891C】Envy
    【BZOJ4883】棋盘上的守卫
    【CF888G】Xor-MST
  • 原文地址:https://www.cnblogs.com/FannyChung/p/3908580.html
Copyright © 2011-2022 走看看