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

前端 未结 5 786
旧时难觅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条回答
  •  萌比男神i
    2020-12-16 18:44

    I had the same problem for std::equal_range and came up with an alternative solution.

    I have a collection of pointers to objects sorted on a type field. I need to find the find the range of objects for a given type.

    const auto range = std::equal_range (next, blocks.end(), nullptr,
        [type] (Object* o1, Object* o2)
    {
        return (o1 ? o1->Type() : type) < (o2 ? o2->Type() : type);
    });
    

    Although it is less efficient than a dedicated predicate as it introduces an unnecessary nullptr test for each object in my collection, it does provide an interesting alternative.

    As an aside, when I do use a class as in your example, I tend to do the following. As well as being shorter, this allows me to add additional types with only 1 function per type rather then 4 operators per type.

    class MSbTLess 
    {
    private:
        static inline const double& value (const MS& val)
        {
            return val.bT;
        }
    
        static inline const double& value (const double& val)
        {
            return val;
        }
    
    public:
        template 
        bool operator() (const T1& lhs, const T2& rhs) const
        {
            return value (t1) < value (t2);
        }
    };
    

提交回复
热议问题