Hi,
Google is being rather unhelpful, as any search for "sorting vectors" inevitably results in std::sort because the unfortunate name of a dynamic array in C++ is "vector".
I wish to sort the following data structure(s) contained withing a list:
struct Vector2
{
int x;
int y;
};
struct Vector3
{
int x;
int y;
int z;
};
The more I play around with the implementation of the overloaded comparison operators, the more I'm lead to believe it's simply not possible to perform the check "A<B" where A and B are both Vector2 or Vector3 objects.
Here's an example program thingy to play around with:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
template <class T>
class Vector2
{
public:
Vector2() {}
Vector2( int x, int y ) : x(x), y(y) {}
~Vector2() {}
int x;
int y;
template <class T_> friend inline bool operator==( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
template <class T_> friend inline bool operator!=( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
template <class T_> friend inline bool operator< ( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
template <class T_> friend inline bool operator> ( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
template <class T_> friend inline bool operator<=( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
template <class T_> friend inline bool operator>=( const Vector2<T_>& lhs, const Vector2<T_>& rhs );
};
template <class T>
inline bool operator==( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
return ( lhs.x==rhs.x && lhs.y==rhs.y );
}
template <class T>
inline bool operator!=( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
return !operator==( lhs, rhs );
}
template <class T>
inline bool operator<( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
if( lhs.x>=rhs.x ) return false;
if( lhs.y>=rhs.y ) return false;
return true;
}
template <class T>
inline bool operator>( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
return operator<( rhs, lhs );
}
template <class T>
inline bool operator<=( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
return !operator>( lhs, rhs );
}
template <class T>
inline bool operator>=( const Vector2<T>& lhs, const Vector2<T>& rhs )
{
return !operator<( lhs, rhs );
}
int main()
{
std::vector< Vector2<int> > myListOfVectors;
for( int n = 0; n != 10; ++n )
myListOfVectors.push_back( Vector2<int>(rand()%100,rand()%100) );
std::sort( myListOfVectors.begin(), myListOfVectors.end() );
for( std::vector< Vector2<int> >::iterator it = myListOfVectors.begin(); it != myListOfVectors.end(); ++it )
std::cout << it->x << "," << it->y << std::endl;
return 0;
}
Any help?