0

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?

myelf
  • 43
  • 5

2 Answers2

1

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(...);
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • to be clear this are 2 options? I don't understand the first one I guess there is a const in there but other than that nothing has changed. – myelf Jul 01 '15 at 17:16
  • @myelf, Yes. These are two options. In your posted code, you had not only missed the `const` but the argument type is `ImpreciseVector`. – R Sahu Jul 01 '15 at 17:18
  • Oh, that ImperciseVector was an artifact from bad editing. Thank you. – myelf Jul 01 '15 at 17:22
1

You don't need to overload the vector, or to change std::less, but to define separately your own std::less compatible function object.

#include <iostream>
#include <vector>
#include <set>
using namespace std;

    struct OppositeVectorComp
    {
        template< class T, class Alloc >
        bool operator()( const std::vector<T,Alloc>& lhs,const std::vector<T,Alloc>& rhs )
        {           
           return   !(lhs < rhs);
        }
    };

int main() {
    std::vector<int> a , b;

    std::set<std::vector<int>> defaultset;
    std::set<std::vector<int>, OppositeVectorComp> myset;

    a.push_back(1);
    b.push_back(2);

    myset.insert(a);
    myset.insert(b);

    defaultset.insert(a);
    defaultset.insert(b);

    std::cout << (*myset.begin())[0] << std::endl; // output 2
    std::cout << (*defaultset.begin())[0] << std::endl; // output 1

    return 0;
}

Here OppositeVectorComp define a new order on vectors where

OppositeVectorComp(a,b) true iff a <b is false

By using the type std::set<std::vector<int>, OppositeVectorComp> we define a set which use the custom std::less.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90