< Previous | Contents | Next >

Introducing the Hero’s Inventory 2.0

Program

From the users point of view, the Heros Inventory 2.0 program is similar to its predecessor, the Heros Inventory program from Chapter 3. The new version stores and works with a collection of string objects that represent a heros inventory. However, from the programmers perspective the program is quite different. Thats because the new program uses a vector instead of an array to represent the inventory. Figure 4.1 shows the results of the program.



image

Figure 4.1

This time the hero’s inventory is represented by a vector.


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_inventory2.cpp.

118 Chapter 4 n The Standard Template Library: Hangman


// Hero’s Inventory 2.0

// Demonstrates vectors


#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");

cout << "You have " << inventory.size() << " items.\n"; cout << "\nYour items:\n";

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

{

cout << inventory[i] << endl;

}


cout << "\nYou trade your sword for a battle axe."; inventory[0] = "battle axe";

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

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

{

cout << inventory[i] << endl;

}


cout << "\nThe item name ’" << inventory[0] << "’ has "; cout << inventory[0].size() << " letters in it.\n";


cout << "\nYour shield is destroyed in a fierce battle."; inventory.pop_back();

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

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

{

Using Vectors 119



cout << inventory[i] << endl;

}


cout << "\nYou were robbed of all of your possessions by a thief."; inventory.clear();

if (inventory.empty())

{


}

else

{


}

cout << "\nYou have nothing.\n";


cout << "\nYou have at least one item.\n";


return 0;

}