< Previous | Contents | Next >

Indexing Vectors

Next I display all of the heros items.

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

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

{

cout << inventory[i] << endl;

}

Just as with arrays, you can index vectors by using the subscripting operator. In fact, the preceding code is nearly identical to the same section of code from the original Heros Inventory program. The only difference is that I used inventory. size() to specify when the loop should end. Note that I made the loop variable i an unsigned int because the value returned by size() is an unsigned integral type.

Next I replace the heros first item.

inventory[0] = "battle axe";

Again, just as with arrays, I use the subscripting operator to assign a new value to an existing element position.


Tra p

image

Although vectors are dynamic, you can’t increase a vector’s size by applying the subscripting operator. For example, the following highly dangerous code snippet does not increase the size of the vector inventory:

vector<string> inventory; //creating an empty vector inventory[0] = "sword"; //may cause your program to crash!

Just as with arrays, you can attempt to access a nonexistent element position—but with potentially disastrous results. The preceding code changed some unknown section of your computer’s memory and could cause your program to crash. To add a new element at the end of a vector, use the push_back() member function.

image