Function object class for less-than inequality comparison

Hello forum,


I have the following structure

1
2
3
4
5
6
7
8
9
10
11
   struct LuminaireProbability
   {
      //luminaire as an intersectable
      Intersectable *mIntersectable;
      //material of the intersectable
      Material *mMaterial;
      //probability of choosing the luminaire
      float mLuminaireProbabilityValue;

   };



And i have a STL vector as follows:

 
std::vector<LuminaireProbability> mLightIntersectables;



I want sort the structure based on the comparion of one of its elements

1
2
3
4
........................
      //probability of choosing the luminaire
      float mLuminaireProbabilityValue;
........................


I am intending to use the less function object into this as follows:

 
std::sort(mLightIntersectables.begin(),mLightIntersectables.end(),std::less<float>());


Logically it is not making any sense to me, since i want to sort the structure based on this float member variable.

Do i have to define an operator inside the structure? If so , please provide me hint on how to do it




Regards
Sajjad
The third parameter of std::sort is supposed to be a functor, an object which has defined the operator().

Either write an object which defines the operator() taking two LuminaireProbability objects and returns based on the comparison, or define the operator< for LuminaireProbability and only pass the first two parameters.

If you need to be able to dynamically choose a different comparison you'll want a functor, but it's easier to define operator<.
Complier does not know how to compare object of your struct since you don't define any function or operator for this.

You should overload the operator< for your objects as @BlackSheep mentioned. This way your compiler would know that you wish your objects to be compared accoriding to their mLuminaireProbabilityValue value and not some other value.

This operator would just return 0 or 1 as a result of the comparison.

Check operator overloading for this.
It iis simple to do with using lambda expressions.


1
2
3
4
5
std::sort( mLightIntersectables.begin(), mLightIntersectables.end(),
               [](  const LuminaireProbability &left, const LuminaireProbability &right )
               {
                   return ( left.mLuminaireProbabilityValue < right.mLuminaireProbabilityValue );
               } );

Topic archived. No new replies allowed.