Here’s an example of how using objects (hat-tip: Paul Wolfensberger)
#include <iostream>
#include <ostream>
#include <vector>
#include <algorithm>
// A base class to hold, return and output a value
class Item
{
private:
int val;
public:
Item( int x )
{
val = x;
}
// Indicate the item type as a string
virtual char* ItemName() = 0;
int GetVal() { return val; }
void OutputToStream( std::ostream& os )
{
os << ItemName() << "\t" << val << "\n";
}
};
// Derived class - "old"
class OldItem : public Item
{
public:
OldItem( int val )
: Item( val ) { }
char* ItemName() { return "Old: "; }
};
// Derived class - "new"
class NewItem : public Item
{
public:
NewItem( int val )
: Item( val ) { }
char* ItemName() { return "New: "; }
};
// Item vector class definition. This class de-allocates
// objects in case you are forgetful.
class ItemVector : public std::vector< Item* >
{
public:
// Avoid leaks by ensuring items are de-allocated
~ItemVector()
{
for ( iterator it = begin();
it != end();
++ it )
{
delete *it;
}
}
};
// Define means of specifying how we want to sort the data:
// Ascending order in this example
struct Ascending
{
bool operator() ( Item*& start, Item*& end )
{
return start->GetVal() < end->GetVal();
}
};
void main()
{
ItemVector itvect;
// Insert some values...
itvect.push_back( new OldItem( 43 ) );
itvect.push_back( new NewItem( 34 ) );
itvect.push_back( new NewItem( 443 ) );
itvect.push_back( new OldItem( 433 ) );
itvect.push_back( new OldItem( 343 ) );
// Sort values in ascending order...
std::sort( itvect.begin(),
itvect.end(),
Ascending() );
// Show the results!
for ( int i = 0; i < (int) itvect.size(); ++i )
{
itvect[ i ]->OutputToStream( std::cout );
}
// Pause for a response
getchar();
}
And here is the output when it is run:
A simpler demonstration using integer arrays:
class descending
{
public:
bool operator()( int x, int y ) const
{
return x > y;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 100, 101, -2, 23, 1010, 44, 55, 3 };
vector<int> v( a, a + 8 );
sort( v.begin(), v.end(), descending() );
copy( v.begin(),
v.end(),
ostream_iterator<int>( cout, " " ) );
return 0;
}
Comments
2 responses to “Sorting Objects Using STL”
Thanks a lot for posting your tips to the world.
I tried your “struct Ascending” on g++. I failed in compiling. I modified it as following and it works.
struct Ascending
{
bool operator() ( Item *start, Item *end )
{
return ( (*start).GetVal() < (*end).GetVal() );
}
};
Thanks for the feedback Tony. I’m not sure why g++ would complain, but you’ve given us a valid alternative.