< Previous | Contents | Next >

Using the sort() Algorithm

Next I sort the scores.

sort(scores.begin(), scores.end());

The sort() algorithm sorts the elements of a sequence in ascending order. You must supply as iterators the starting and ending points of the sequence to sort. In this particular case, I passed the iterators returned by scores.begin() and scores.end(). These two iterators indicate that I want to sort all of the elements in scores. As a result, scores contains all of the scores in ascending order.

Finally, I display the scores to prove the sorting worked.


Tric k

image

A very cool property of STL algorithms is that they can work with containers defined outside of the STL. These containers only have to meet certain requirements. For example, even though string objects are not part of the STL, you can use appropriate STL algorithms on them. The following code snippet demonstrates this:

string word = "High Scores"; random_shuffle(word.begin(), word.end());

The preceding code randomly shuffles the characters in word. As you can see, string objects have both begin() and end() member functions, which return iterators to the first character and one past the last character, respectively. That’s part of the reason why STL algorithms work with strings—because they’re designed to.

image

136 Chapter 4 n The Standard Template Library: Hangman