sorting an std::list?

Started by
8 comments, last by psykr 20 years, 4 months ago
I have an std::list of ObjectIDs, and I want to add ObjectIDs to the list one by one. Is there any way that I can specify that I want the items inserted to be sorted, short of doing it by hand?
Advertisement
If you want the items to be sorted use a std:riority_queue, std::set or std::multiset
Oops it is supposed to be std:: priority_queue. I quess "; p" when typed without the space between them becomes the smiley -
Sure, there is a sort algorithm in the standard libraries. You specify a comparison function. Search for stl sort in google, you''ll find all the info you need, and better than I can describe it.
If the items in the list are Objects of a class, you can also overload the > operater and then you can call theList.sort() and it will sort it.
quote:Original post by Ataru
Sure, there is a sort algorithm in the standard libraries. You specify a comparison function. Search for stl sort in google, you''ll find all the info you need, and better than I can describe it.


This doesn''t work for lists. std::sort needs a random access iterator. A list has it''s own sort function: list.sort()


My Site
You''re right, I only ever use vectors for automatic sorting, but that makes complete sense. Sorry for misleading.
quote:Original post by Brad8383
If the items in the list are Objects of a class, you can also overload the > operater and then you can call theList.sort() and it will sort it.


What if I''m sorting pointers? For example, std::list<Object*>? If I overloaded the > operator, would it still sort? Sorry, no access to a C++ compiler lately.
it would then sort on the value of the pointer
You can create a binary predicate function (or functor) and pass the function to sort instead of overloading < operator.

Example:

#include <list>
#include <functional>

class Object {
//...
};

//function
bool my_compare(Object * o1, Object * o2) {
if (o1->whatever < o2->whatever) return true;
return false;
}

//functor
class my_compare_f {
public:
my_compare_f() : n(0) {}
bool operator()(Object * o1, Object * o2) {
n++; return my_compare(o1, o2);
}
int n;
};

//...
std::list<object *> myList, myList2;
//...

myList.sort(my_compare);
my_compare_f c;
myList2.sort(c);
//c.n holds number of comparisons
Kevin.

This topic is closed to new replies.

Advertisement