< Previous | Contents | Next >

Introducing the Inventory Displayer

Program

The Inventory Displayer program creates a vector of strings that represents a heros inventory. The program then calls a function that displays the inventory. The program passes the displayer function the vector of items as a reference, so its an efficient call; the vector isnt copied. However, theres a new wrinkle. The program passes the vector as a special kind of reference that prohibits the displayer function from changing the vector. Figure 6.3 shows you the program.

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


image

Figure 6.3

The vector inventory is passed in a safe and efficient way to the function that displays the hero’s items.

196 Chapter 6 n References: Tic-Tac-Toe


// Inventory Displayer

// Demonstrates constant references


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


using namespace std;


//parameter vec is a constant reference to a vector of strings void display(const vector<string>& inventory);


int main()

{

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


display(inventory);


return 0;

}


//parameter vec is a constant reference to a vector of strings void display(const vector<string>& vec)

{

cout << "Your items:\n";

for (vector<string>::const_iterator iter = vec.begin(); iter != vec.end(); ++iter)

{

cout << *iter << endl;

}

}