C++ lambdas for std::sort and std::lower_bound/equal_range on a struct element in a sorted vector of structs

前端 未结 5 783
旧时难觅i
旧时难觅i 2020-12-16 18:10

I have a std::vector of this struct:

struct MS
{        
  double aT;
  double bT;
  double cT;
};

which I want to use std::sort on aswell

5条回答
  •  温柔的废话
    2020-12-16 18:53

    Not directly relevant to what you're saying about lambdas, but this might be an idea for using the binary search functions:

    #include 
    #include 
    #include 
    
    struct MS
    {
        double aT;
        double bT;
        double cT;
        MS(double a, double b, double c) : aT(a), bT(b), cT(c) {}
    };
    
    // template parameter is a data member of MS, of type double
    template 
    struct Find {
        double d;
        Find(double d) : d(d) {}
    };
    
    template 
    bool operator<(const Find &lhs, const Find &rhs) {
        return lhs.d < rhs.d;
    }
    template 
    bool operator<(const Find &lhs, const MS &rhs) {
        return lhs.d < rhs.*F;
    }
    template 
    bool operator<(const MS &lhs, const Find &rhs) {
        return lhs.*F < rhs.d;
    }
    
    int main() {
        std::cout << (Find<&MS::bT>(1) < Find<&MS::bT>(2)) << "\n";
        std::cout << (Find<&MS::bT>(1) < MS(1,0,0)) << "\n";
        std::cout << (MS(1,0,0) < Find<&MS::bT>(1)) << "\n";
    
        std::vector vec;
        vec.push_back(MS(1,0,0));
        vec.push_back(MS(0,1,0));
        std::lower_bound(vec.begin(), vec.end(), Find<&MS::bT>(0.5));
        std::upper_bound(vec.begin(), vec.end(), Find<&MS::bT>(0.5));
    }
    

    Basically, by using Find as the value, we don't have to supply a comparator, because Find compares to MS using the field that we specify. This is the same kind of thing as the answer you saw over here: how to sort STL vector, but using the value rather than the comparator as in that case. Not sure if it'd be all that great to use, but it might be, since it specifies the value to search for and the field to search in a single short expression.

提交回复
热议问题