Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
This is the answer of Exercise #4: Reading from a std::vector safely.
First, I start this answer with one of my favorite quotes:
Van mijn std::vector bestaat deze index zeker. |
#include <cstdlib> |
It might be true that the variable 'index' is not a valid index of std::vector 'v':
#0) at the time 'maxIndex' was defined, the std::vector 'v' might have changed in size
#1) at the time 'index' was defined, the std::vector 'v' might have changed in size
You assume that 'index' is a valid index of std::vector 'v'.
So use assert:
v[index] = 0; |
Writing asserts for each std::vector access is not necessary.
If the std::vector in this exercise was a const std::vector, you can be 100% sure that it did not change in size, so you can be sure the std::vector access is valid.
If short pieces of code (IMHO: 5 lines) in which you do not see an change of std::vector's size, you can be 99,9% sure that std::vector access is valid. Be aware that this short piece of code can expand in time, decreasing the certainty that the access is valid.
If your program gives an access violation (perhaps in the form of external exception EEFFACE), it will always be time-inexpensive to add assert. And you might have found the problem. To again quote many of my students 'I am sure that this is a valid index in my std::vector'. How often have they been wrong...
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.