Why does the last expected output differ from the actual output in the following code?
#include<iostream>
#include<fstream>
#include<istream>
#include<sstream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
for(int ii = 0; ii < 4; ii++){
v.push_back(0);
}
vector<vector<int>> twoDv;
for(int ii = 0; ii < 5; ii++){
twoDv.push_back(v);
}
cout<<"Expected Output : " << &twoDv[0][0] <<'\t'<< (&twoDv[0][0] + 3) <<'\t'<< (&twoDv[0][3] + 1)<<'\n';
cout<<"Actual Output : " << &twoDv[0][0] <<'\t'<< &twoDv[0][3] <<'\t'<< &twoDv[1][0] << '\n';
}
The standard doesn’t say that
&twoDv[1][0]is equal to&twoDv[0][3] + 1. It says that&twoDv[1]is equal to&twoDv[0] + 1, and that&twoDv[0][1]is equal to&twoDv[0][0] + 1.Suppose for a moment that
&twoDv[1][0]were equal to&twoDv[0][3] + 1, and then you didtwoDv[0].resize(5);. Suddenly we have a conflict,&twoDv[0][3] + 1can’t be the address of&twoDv[1][0]and also the address of&twoDv[0][4]. So the resize operation ontwoDv[0]would have to invalidate iterators and references to the elements of another vectortwoDv[1]. This would be very undesirable behavior.