Skip to main content
gamedev.net
🔒 Locked

stl sort

Started by Brad8383 6 replies 450+ views
Original Post
Brad8383
Brad8383
I cant find any examples of comparision functions used in my stl book so I was wondering if anyone good give me a simple example. I have a list of objects list<object> and object is a class with x and y. i want to sort in ascending order x*y. (Edit: Don't type <object> without using &lt and &rt around the word object, or it treats it as an object tag in HTML and breaks the thread. Now fixed. -- Kylotan.) Edited by - Kylotan on December 16, 2001 6:53:54 PM
Shannon Barber
Shannon Barber
For list you call the std::list::sort method, not the std::sort algorithm, and I''m pretty sure you need to write a functor (function object - overload operator() ) to perform you comparison and pass it as a parameter to the sort method.

Magmai Kai Holmlor
- Not For Rent
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Brad8383
Brad8383
How do i setup the function i send it
invective
invective
std::list.sort () takes no parameters and needs no functor. However, whatever object is being stored in the list must have operator < defined for the sort comparison. If the data type being stored is not a primitive type (like int, float, char, etc.) you must overload the < operator for your class, otherwise the sort algorithm has no idea how to sort your data.

  
#include <iostream>
#include <list>


void main( void )
{
std::list<int> mylist;
mylist.push_back(5);
mylist.push_back(4);
//List is now 5,4

mylist.sort();
//Now the list is 4,5

//So the following statement will print out 4

std::cout << *(mylist.begin());

}
sporty
sporty
wtf?
Brad8383
Brad8383
The solution that I''m looking for I have done before. Problem is I can''t remember. The list was a list of obj classes with x and y coords and i ordered them by x*y. I remember having to pass a function pointer to the sort function. It had 2 parameters with each one being a class and it returned whichever one''s x*y value was higher. I just need help on the syntax. I have no idea what type of function it should be,return value, etc.
invective
invective
Sounds like you are talking about C''s qsort function rather than std::list.sort or the algorithm sort in C++.

see here:
http://www.cplusplus.com/ref/cstdlib/qsort.html
Brad8383
Brad8383
nevermind im stupid. that function i was thinking about is none other than the < overloaded operator itself. oh well everything works now

Topic Locked

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

Sign in to reply to this topic.