< Previous | Contents | Next >

Accessing Member Functions of a Vector Element

Next I display the number of characters in the name of the first item in the heros inventory.

cout << "\nThe item name ’" << *myIterator << "’ has "; cout << (*myIterator).size() << " letters in it.\n";

The code (*myIterator).size() says, Take the result of dereferencing myIterator and call that objects size() member function.Because myIterator refers to the string object equal to "battle axe", the code returns 10.


Hin t

image

Whenever you dereference an iterator to access a data member or member function, surround the dereferenced iterator by a pair of parentheses. This ensures that the dot operator will be applied to the object the iterator references.

image


The code (*myIterator).size() is not the prettiest, so C++ offers an alternative, more intuitive way to express the same thing, which I demonstrate in the next two lines of the program.

cout << "\nThe item name ’" << *myIterator << "’ has "; cout << myIterator->size() << " letters in it.\n";

The preceding code does exactly the same thing the first pair of lines I presented in this section do; it displays the number of characters in "battle axe". However, notice that I substitute myIterator->size() for (*myIterator).size(). You can see that this version (with the -> symbol) is more readable. The two pieces of code mean exactly the same thing to the computer, but this new version is easier for humans to use. In general, you can use the -> operator to access the member functions or data members of an object that an iterator references.

130 Chapter 4 n The Standard Template Library: Hangman


Hi n t

image

Syntactic sugar is a nicer, alternative syntax. It replaces harsh syntax with something that’s a bit easier to swallow. As an example, instead of writing the code (*myIterator).size(), I can use the syntactic sugar provided by the -> operator and write myIterator->size().

image