< Previous | Contents | Next >

Introducing the Hero’s Inventory 3.0

Program

The Heros Inventory 3.0 program acts like its two predecessors, at least at the start. The program shows off a list of items, replaces the first item, and displays the number of letters in the name of an item. But then the program does something new: It inserts an item at the beginning of the group, and then it removes an item from the middle of the group. The program accomplishes all of this by working with iterators. Figure 4.2 shows the program in action.



image

Figure 4.2

The program performs a few vector manipulations that you can accomplish only with iterators.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 4 folder; the filename is heros_inventory3.cpp.

124 Chapter 4 n The Standard Template Library: Hangman


// Hero’s Inventory 3.0

// Demonstrates iterators


#include <iostream> #include <string> #include <vector>

using namespace std; int main()

{

vector<string> inventory; inventory.push_back("sword"); inventory.push_back("armor"); inventory.push_back("shield");


vector<string>::iterator myIterator; vector<string>::const_iterator iter;


cout << "Your items:\n";

for (iter = inventory.begin(); iter != inventory.end(); ++iter)

{

cout << *iter << endl;

}


cout << "\nYou trade your sword for a battle axe."; myIterator = inventory.begin();

*myIterator = "battle axe"; cout << "\nYour items:\n";

for (iter = inventory.begin(); iter != inventory.end(); ++iter)

{

cout << *iter << endl;

}


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


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

Using Iterators 125


cout << "\nYou recover a crossbow from a slain enemy."; inventory.insert(inventory.begin(), "crossbow"); cout << "\nYour items:\n";

for (iter = inventory.begin(); iter != inventory.end(); ++iter)

{

cout << *iter << endl;

}


cout << "\nYour armor is destroyed in a fierce battle."; inventory.erase((inventory.begin() + 2));

cout << "\nYour items:\n";

for (iter = inventory.begin(); iter != inventory.end(); ++iter)

{

cout << *iter << endl;

}


return 0;

}