< Previous | Contents | Next >
Okay, the first thing I do in main() is declare a new vector.
vector<string> inventory;
The preceding line declared an empty vector named inventory, which can contain string object elements. Declaring an empty vector is fine because it grows in size when you add new elements.
To declare a vector of your own, write vector followed by the type of objects you want to use with the vector (surrounded by the < and > symbols), followed by the vector name.
120 Chapter 4 n The Standard Template Library: Hangman
Hi n t
There are additional ways to declare a vector. You can declare one with a starting size by specifying a number in parentheses after the vector name.
vector<string> inventory(10);
The preceding code declared a vector to hold string object elements with a starting size of 10. You can also initialize all of a vector’s elements to the same value when you declare it. You simply supply the number of elements followed by the starting value, as in:
vector<string> inventory(10, "nothing");
The preceding code declared a vector with a size of 10 and initialized all 10 elements to
"nothing". Finally, you can declare a vector and initialize it with the contents of another vector.
vector<string> inventory(myStuff);
The preceding code created a new vector with the same contents as the vector myStuff.