Search code examples
c++stdset

how to use std::find with an < operator that is not std::less


say I have

class newVector: public std::vector<T> {
    public:
        bool operator< (const newVector& v) { 
            //..
        }
};

And

a std::set<newVector>; 

I can't manage to use a.find(...) properly, I am not sure what to put into the (...) in order to use newVector::operator<. When I just put a.find(element) it uses std::less. Should I change std::less somehow?


Solution

  • Ignoring for the time being that deriving from std::vector is a bad idea, I can think of the following ways to address the issue:

    1. Define operator< for objects of newVector.

      class newVector: public std::vector<T> {
          public:
              bool operator< (const newVector& v) const { 
                  //..
              }
      

      and

      std::set<newVector> a;
      a.find(...);
      
    2. Define a functor that has appropriate operator() function and use it to create the std::set.

      template <typename T>
      struct NewVectorLess
      {
         bool operator()(newVector<T> const& lhs, newVector<T> const& rhs)
         {
           // ...
         }
      };
      

      and

      std::set<newVector<int>, NewVectorLess<int>> a;
      a.find(...);