I tried taking a list and pass it through std::sort like the following:
sort(Unsorted.begin(), Unsorted.end());
I got an error back stating that the list iterator doesn't have a
binary substraction operator.
Peeking in the algoritm header file it's clear why seeing that sort
there calls _sort(_First, _Last, _Last-_First) which might be a tad
challenging seeing that the different values stored in a list do not
need to be stored consecutively.
My question is there another way to sort the list in the STL?
For a very good STL reference (especially if your STL implementation is
SGI's, which is fairly common I think (its free)), look at
http://www.sgi.com/tech/stl/
There, we see (
http://www.sgi.com/tech/stl/sort.html):
template <class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class StrictWeakOrdering>
void sort(RandomAccessIterator first, RandomAccessIterator last,
StrictWeakOrdering comp);
Complexity
O(N log(N)) comparisons (both average and worst-case), where N is last -
first. [2]
So the sort function only takes Random Access Iterators, whereas
list::iterator is a Bidirectional Iterator.
Thus, we go to the list page (
http://www.sgi.com/tech/stl/List.html),
and we have:
New members
These members are not defined in the Reversible Container, Front
Insertion Sequence, and Back Insertion Sequence requirements, but are
specific to list.
----
void sort(); Sorts *this according to operator<. The sort is stable,
that is, the relative order of equivalent elements is preserved. All
iterators remain valid and continue to point to the same elements. [6]
The number of comparisons is approximately N log N, where N is the
list's size.
----
[6] The sort algorithm works only for random access iterators. In
principle, however, it would be possible to write a sort algorithm that
also accepted bidirectional iterators. Even if there were such a version
of sort, it would still be useful for list to have a sort member
function. That is, sort is provided as a member function not only for
the sake of efficiency, but also because of the property that it
preserves the values that list iterators point to.
So, use the list::sort() function to sort a list, or if you need a
comparison function other than STL's less functor, there is a member
template version of list::sort(BinaryPredicate Comp) which lets you do that.
One warning: if you are not using SGI's STL, then watch out for SGI
extensions to the standard on this reference site.