When accessing vector data with indices, the most common problem we can run into is exceeding the vector's bounds.
Remember, the items of a vector are indexed from 0 to size - 1. Any index which is not in this range is invalid.
When you read an item with an invalid index, C++ doesn't stop you. The program reads memory that isn't part of the vector. It may print a random number, or it may crash. This is called undefined behavior.
vector<int> myArray = {50, 40, 30};
// Valid indices: 0, 1, 2
cout << myArray[0] << endl; // Output: 50
cout << myArray[2] << endl; // Output: 30
// Invalid indices: 3, 30, -1
cout << myArray[3] << endl; // undefined: a random value, or a crash
cout << myArray[30] << endl; // undefined: a random value, or a crash
cout << myArray[-1] << endl; // undefined: a random value, or a crash
If you want an error instead, read with at(). It checks the index first:
cout << myArray.at(3) << endl; // throws an out_of_range error
As programmers, we always want to make sure that we don't exceed one vector's bounds in our programs.
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
