Chaining of ordering predicates (e.g. for std::sort)

前端 未结 6 1940
说谎
说谎 2021-02-05 23:33

You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.

Howeve

6条回答
  •  感动是毒
    2021-02-06 00:21

    Variadic templates in C++ 11 give a shorter option:

        #include 
        using namespace std;
    
        struct vec { int x,y,z; };
    
        struct CmpX {
          bool operator() (const vec& lhs, const vec& rhs) const 
          { return lhs.x < rhs.x; }
        };
    
        struct CmpY {
          bool operator() (const vec& lhs, const vec& rhs) const 
          { return lhs.y < rhs.y; }
        };
    
        struct CmpZ {
          bool operator() (const vec& lhs, const vec& rhs) const 
          { return lhs.z < rhs.z; }
        };
    
        template 
        bool chained(const T &, const T &) {
          return false;
        }
    
        template 
        bool chained(const T &t1, const T &t2, const CMP &c, P...p) {
          if (c(t1,t2)) { return true;          }
          if (c(t2,t1)) { return false;         }
          else          { return chained(t1, t2, p...); }
        }
    
        int main(int argc, char **argv) {
          vec x = { 1,2,3 }, y = { 2,2,3 }, z = { 1,3,3 };
          cout << chained(x,x,CmpX(),CmpY(),CmpZ()) << endl;
          return 0;
        }
    

提交回复
热议问题