Sorting a STL List

Hi Everyone

I am struggling to sort a STL list I have created. I have tried using the .sort() function however when I try to compile the program (using visual studio) it gives me a large amount of errors and compilation fails.

At the moment I have the following to go through the list:

1
2
3
4
5
6

	for(listIterator1 = list.begin(); listIterator1 != list.end(); listIterator1++)
  	{
			

	}


I am unsure how to (within the for loop) compare the elements of the list enabling me to sort them, at first I thought they could just be treated like an array (i.e if (array[i] < array[i + 2] )) But clearly this isn't the case.

If someone could point me in the right direction I would be very grateful.

Thank you :)
You need to find (or create) a sort algorithm that can work with bidirectional iterators. std::sort() (http://www.cplusplus.com/reference/algorithm/sort/) requires random access iterators.

Let me ask you this: does it have to be an in-place sort?
Use list<>::sort() http://en.cppreference.com/w/cpp/container/list/sort


1
2
3
std::list<int> lst = { 32, 5, 36, 478, 68, 976, 32, 2537, 89, 70, 73, 353 } ;
lst.sort() ; // sort in ascending order
lst.sort( std::greater<int>() ) ; // sort in descending order 

Topic archived. No new replies allowed.