< Previous | Contents | Next >
Introducing the Inventory Displayer
The Inventory Displayer program creates a vector of strings that represents a hero’s 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 it’s an efficient call; the vector isn’t copied. However, there’s 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.
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;
}
}