1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Here's my element type: a point in space.
struct point_t
{
int x, y;
point_t( int x = 0, int y = 0 ):
x( x ),
y( y )
{ }
bool sortfunc( const point_t& lhs, const point_t& rhs ) const
{
return (lhs.x == rhs.x)
? (lhs.y < rhs.y)
: (lhs.x < rhs.x);
}
};
// Here's my comparitor for the sort() function to use.
bool operator < ( const point_t& lhs, const point_t& rhs )
{
return lhs.sortfunc( lhs, rhs );
}
// The rest of this stuff is just to display a point...
ostream& operator << ( ostream& outs, const point_t& point )
{
return outs << "(" << point.x << "," << point.y << ")";
}
// ...and a list of points
ostream& operator << ( ostream& outs, const vector <point_t> & points )
{
for (unsigned n = 0;;)
{
outs << points[ n ];
if (++n >= points.size()) break;
outs << ", ";
}
return outs;
}
// Enjoy!
int main()
{
vector <point_t> v;
v.push_back( point_t( 10, -7 ) );
v.push_back( point_t( -2, 14 ) );
v.push_back( point_t( 3, 5 ) );
v.push_back( point_t( 3, 0 ) );
v.push_back( point_t( 3, 78 ) );
v.push_back( point_t( 24, 42 ) );
cout << "v = " << v << endl;
cout << "sorting v..." << flush;
sort( v.begin(), v.end() );
cout << "done.\n";
cout << "v = " << v << endl;
return 0;
}
|