|
-
November 25th, 2002, 09:18 PM
#1
List.h sort() Function
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!!
-
November 25th, 2002, 10:11 PM
#2
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
-
November 25th, 2002, 10:52 PM
#3
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).
Code:
#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;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|