-1

I was playing around with nested vectors and printing random elements to see the output and I noticed that when I go out of bounds I don't get an error. I simply get 0 returned as the value.

Why is this?

Is the vector being resized and initialized to zero whenever I attempt to call an out-of-bounds element by index?

Here's the code I was running:

#include <iostream>
#include <vector>


int main(){
  std::vector<std::vector<int>> matrix;
  std::vector<int> temp;
  temp.push_back(1);
  temp.push_back(2);
  matrix.push_back(temp);
  std::cout << matrix[0][45] << std::endl;

  return 0;
}
somerandomdude
  • 337
  • 3
  • 15

1 Answers1

1

You're having undefined behavior, that it prints 0 is just a mere coincidence.

deW1
  • 5,562
  • 10
  • 38
  • 54