Click to See Complete Forum and Search --> : List.h sort() Function
hopestar
November 25th, 2002, 08:18 PM
I want to create a list of the following structure:
struct Element() {
int node;
int timestamp;
}
list<Element *> elementList;
Is there a way to use the .sort() function from the list.h class to sort elementList ONLY by the timestamp?? If not, are there any other suggestions for doing this in an easy manner? Thanks in advance for any help!!
vinodp
November 25th, 2002, 09:11 PM
To work sort with list U need to define comparison operator <(less than)for ur struct or class.
Define that operator in ur struct. & just compare timestamp value there
Vinod
Philip Nicoletti
November 25th, 2002, 09:52 PM
Here is an example. Some notes :
if your compiler supports it, you should use #include <list> , not <list.h>
the code below uses the predicate form of the sort() member function.
Old version of Visual C++ do not support this (you can get an upgrade
from dinkumware - but its not free).
#include <list>
#include <iostream>
struct Element
{
int node;
int timestamp;
};
struct sort_by_timestamp
{
inline bool operator () (const Element * lhs , const Element * rhs) const
{
return lhs->timestamp < rhs->timestamp;
}
};
int main()
{
std::list<Element *> elementList;
std::list<Element *>::iterator iter;
Element *p;
p = new Element;
p->node = 0;
p->timestamp = 90;
elementList.push_back(p);
p = new Element;
p->node = 1;
p->timestamp = 50;
elementList.push_back(p);
p = new Element;
p->node = 2;
p->timestamp = 80;
elementList.push_back(p);
//--- print list before sort
std::cout << "unsorted list" << std::endl;
for(iter=elementList.begin(); iter!=elementList.end(); ++iter)
std::cout << (*iter)->timestamp << " " << (*iter)->node << std::endl;
//--- sort list by timestamp
elementList.sort( sort_by_timestamp() );
//--- print sorted list
std::cout << std::endl << "sorted list by timestamp" << std::endl;
for(iter=elementList.begin(); iter!=elementList.end(); ++iter)
std::cout << (*iter)->timestamp << " " << (*iter)->node << std::endl;
//--- cleanup
for(iter=elementList.begin(); iter!=elementList.end(); ++iter)
{
delete *iter;
}
elementList.clear();
return 0;
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.