views:

172

answers:

1

Hello I have some touble overloading operators for std::list.

I store pairs in a list, consisting in an int value and a position array :

  typedef std::pair< int, std::vector<int,3> > pointPairType;
  typedef std::list< pointPairType > pointListQueueType;
  pointListQueueType pointsQueue;
  // adding some points to the list

And I would like to sort the list according to the first value of the pair, I though that would work :

creating a comparison class,

and feeding the short algorithm with it :

// comparison function
template < class T1, class T2 >
class compareFirst
{
  public:
  bool operator() (const std::pair<T1,T2>& l, const std::pair<T1,T2>& r)
    {
    return l.first < r.first;
    }
};

... and in main :

  // use of sorting algorithm : error here
  pointsQueue.sort(< int, std::vector<int,3> >compareFirst);

But I get an "expected primary expression before '<' token

Any help would be greatly appreciated ! thanks !

+4  A: 

The first problem is that there is no such type std::vector<int, 3>. Assuming you meant to use 3-element arrays, std::array<int, 3> (or std::tr1::array or boost::array, depending on the compiler) is what you need, or just std::vector<int>.

Secondly, those int and std::vector<int, 3> are template parameters that tell the compiler to select between many possible compileFirst's. They go after the identifier to which they apply, not before it.

The following compiles and runs on GCC 4.5.2 and MSVC 2010:

#include <list>
#include <array>
typedef std::pair< int, std::array<int, 3> > pointPairType;
typedef std::list< pointPairType > pointListQueueType;
pointListQueueType pointsQueue;
template < class T1, class T2 >
struct compareFirst
{
    bool operator() (const std::pair<T1,T2>& l, const std::pair<T1,T2>& r) const
    {
        return l.first < r.first;
    }
};
int main()
{
    pointsQueue.sort(compareFirst< int, std::array<int,3> >());
}
Cubbi
thanks a lot for this very detailed answer. Indeed, I wrote the example too quikly (std::vector mistake). Thanks again !
Antonin