jeudi 21 novembre 2019

Problem with maximum index value of a vector

I have a strange problem regarding a vectors range. Take into account this code :

#include <iostream>
#include <vector>

using namespace std;
int main(){
  int n(0);
  vector<int> tab(n);
  tab[n] = 5;
  cout << tab[n];
}


The code displays a segfault when the size of the vector isn't declared, which makes sense. But it displays 5 when n has a given value, which DOES NOT work when n is 6 plus a multiple of 4 (i.e 6,10,14 etc). From theory the maximum index of an element must be tab.size()-1 so why does it happen?

Thank you in advance for answering!

Aucun commentaire:

Enregistrer un commentaire