Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) Exercise #4: Reading from a std::vector safely

 

Difficulty: 1/10

Date added: 13th of July 2008

 

In this exercise, you must think about problems that might occur and how to prevent these.

 

Answer the following questions about the code below:

0) What problem might occur?

1) How can you prevent this?

 

 

#include <vector>

#include <cstdlib>

 

int main()

{

std::vector<int> v;

 

//Lots of code

 

const int maxIndex = v.size();

 

//Lots of code

 

const int index = std::rand() % maxIndex; //Draw a random index

 

//Lots of code

 

v[index] = 0;

 

//Lots of code

}

 

 

 

View the answer of this exercise.

 

 

 

 

 

Post your feedback

 

Feel free to post your feedback about this exercise at Programmer's Heaven.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.