Click to See Complete Forum and Search --> : Q: STL list.sort


ChristianH
August 3rd, 1999, 06:32 AM
How to sort my list by m_id???
Thank you in advance for every answer.


#include <iostream>
#include <list>
using namespace std;

class C {
public:
int m_id;
C( int i) { m_id=i; }
};

void main()
{
list< C* > l;
l.push_back( new C(2));
l.push_back( new C(4));
l.push_back( new C(1));

l.sort(); // sorted by the pointer to C

list< C* >::iterator itr;
for( itr=l.begin(); itr!=l.end(); itr++)
cout << (*itr)->m_id;
}




I suppose I need something like but don't know it exactly:

bool operator>( const C* pc1, const C* pc2) {
return pc1->m_id > pc2->m_id;
}

Joe DeCarlo
August 4th, 1999, 06:50 PM
//use the sort algorithm
//(as in your example...)
#include <iostream>
#include <list>
#include <algo.h>

using namespace std;

class C
{
public:
int m_id;
C(int i) { m_id=i; }
};

void main()
{
list< C* > l;
l.push_back( new C(2));
l.push_back( new C(4));
l.push_back( new C(1));

list<C*>::iterator b = l.begin();
list<C*>::iterator e = l.end();

// you will need to write a compare function
//so use something like...

sort(b, e, sort_c_pointers());

b = l.begin();
e = l.end();

for(b; b != e; ++b)
{
cout << (*b)->m_id;
}
}

//Here is the functor you should make to tell the sort function how to sort your class:
struct sort_c_pointers : public binary_function<C*, C*, bool>
{
bool operator()(C* x, C* y)
{
return x->m_id < y->m_id;
}
};

Excuse the unconventional lack of tabbing, but this editor doesn't seem to notice that I put them in there

ChristianH
August 5th, 1999, 03:11 AM
Well, this answer wasn't quite correct.
The principle is well, but it doesn't work. Try to compile it => :-((
The main problem with the STL is the lack of readable documentation.
However, I found the solution!
sort() requires an "random-access-iterator" - and they are only given by vector and deque, not by list!