|
From: Eddy L O J. <ed...@kl...> - 2002-08-18 10:10:42
|
2002-08-18 10:46:45, "Abhijit Shylanath" <mu...@gm...> wrote:
>I'm using a vector of a structure pointer (I use dynamic
>allocation), like
I'm in a good mood today, so I wrote you up a short example using
a functor predicate. I'm sure it can be solved using an overloaded
operator<() too, that's just now how I'd do it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
class on_age
{
public:
bool operator() (const T& v1, const T& v2) const
{
return v2->age_ > v1->age_;
}
};
struct t_person
{
t_person(const string& name, int age) : name_(name), age_(age)
{ };
string name_;
int age_;
};
int main(int argc, char *argv[])
{
vector<t_person*> people;
vector<t_person*>::const_iterator it;
people.push_back( new t_person("Gordon", 31) );
people.push_back( new t_person("Tiny", 1) );
people.push_back( new t_person("Alice", 16) );
people.push_back( new t_person("Second", 2) );
people.push_back( new t_person("Grandpa", 101) );
sort(people.begin(), people.end(), on_age<t_person*>() );
for( it = people.begin() ; it != people.end() ; ++it )
cout << (*(it))->name_ << ", " << (*(it))->age_ << endl;
// yeah, yeah, "leak". Whatever
return 0;
}
--
"Reading this line brought you three seconds closer to death."
Eddy L O Jansson | http://gazonk.org/~eloj
|