< Previous | Contents | Next >

Iterating through string Objects

Given your new knowledge of for loops and string objects, its a snap to iterate through the individual characters of a string object. Thats what I do next:

for (unsigned int i = 0; i < phrase.size(); ++i)

{

cout << "Character at position " << i << " is: " << phrase[i] << endl;

}

94 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


The loop iterates through all of the valid positions of phrase. It starts with 0 and goes through 11. During each iteration, a character of the string object is displayed with phrase[i]. Note that I made the loop variable, i, an unsigned int because the value returned by size() is an unsigned integral type.


Rea l Worl d

image

Iterating through a sequence is a powerful and often-used technique in games. You might, for example, iterate through hundreds of individual units in a strategy game, updating their status and order. Or you might iterate through the list of vertices of a 3D model to apply some geometric transformation.

image