Skip to main content
gamedev.net
🔒 Locked

sorting problems

Started by ekrax 3 replies 1k views
Original Post
ekrax
ekrax
hello, i've come to a point in my project where i need to sort some objects based on their vertical position. im using a vector for the objects, which i'm going to hafta change to a list since i wasnt thinking ahead. but im not sure how to sort using the sort member function. in my book it says i can pass it a comparison function. but it gives no examples and im not clear on the syntax. i also tried using vectors and coverting to a standard array and then use qSort (waste of memory, but i just wanted to try it out) ... i could get that to work either, since the compare function prototype is ... int comp (const void *, const void *) and i coudnlt get it to sort the y variable of my obj class. so i can see the sort in the list class is like this ... void sort(Comp cmpfn); how do i use this function? thanks for any help in advance.
pammatt
pammatt
The STL sort method does not work on lists, that's why list has its own sort method. They all work by using the objects less-than operator when comparing.

//Define the less-than operator for the class SomeObjstd::vector<SomeObj> v;//Add elements...//Sort the vector is ascending orderstd::sort(v.begin(), v.end());


Something like the above code. Just google for STL vector and list and you will see examples of how to use the sort methods.
ekrax
ekrax
so i basically have to overload < operator for my class and tell it to compare it's y variable.

so once i have overloaded < and do this ...
std::sort(v.begin(), v.end());

STL will do the rest?
pammatt
pammatt
Yep.
snk_kid
snk_kid
Quote:
Original post by ekrax
so i basically have to overload < operator for my class and tell it to compare it's y variable.

so once i have overloaded < and do this ...
std::sort(v.begin(), v.end());

STL will do the rest?


That is not the only way, you don't have to overload relational operators, you can use member functions/free-functions/functor e.g.

#include <iterator>#include <algorithm>#include <list>#include <iostream>struct foo {  int i;  foo(int j = 0): i(j) {}};std::ostream& operator<<(std::ostream& out, const foo& f) {   return (out << f.i);}bool compare(const foo& f1, const foo& f2) {   return f1.i < f2.i;}int main() {  std::list<foo> foo_list;  foo_list.push_back(3);  foo_list.push_back(1);  foo_list.push_back(8);  foo_list.push_back(6);  std::copy(foo_list.begin(), foo_list.end(),            std::ostream_iterator<foo>(std::cout, "\n"));  std::cout << "\n\nsorting list\n";  foo_list.sort(compare);  std::copy(foo_list.begin(), foo_list.end(),            std::ostream_iterator<foo>(std::cout, "\n"));}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.