0
vector <int> x = {1,2,3};
vector <int> y = {4,5,6};

With a bit of simplification on the code, I have two vector variable representing above array of values. I was working on something and learned that when I do

cout << x[-1] << endl;

it output will be

6

Based on the above experiment, the vector data structure stores data like this,

{4,5,6,1,2,3}

However, I do not think this is very safe, as one vector variable can access other vector variable, which can make unexpected error for amateur programmer like me.

I want to know if my above statement is valid, or I am misunderstanding something. I thought that having index variables unsigned can solve this issue, but I still want to know that I am understanding the visual structure clearly.

I have read something about unpredictability in assignment, so that can be the case as well.

Can someone help me clear this out?

Thank you very much.

trincot
  • 317,000
  • 35
  • 244
  • 286
BitsofEthan
  • 101
  • 1
  • 5
  • 4
    ***However, I do not think this is very safe, as one vector variable can access other vector variable*** It is not safe. Its undefined behavior. `c++` does not prevent you from doing this. The result need not have been the other array. There is no guarantee what happens when you have undefined behavior. – drescherjm Nov 23 '16 at 02:34
  • It could also have outputted your social security number... Or kittens... Or a unicorn... Or crashed.. Or... Welcome to UB... – Macmade Nov 23 '16 at 02:36
  • ***Based on the above experiment, the vector data structure stores data like this,*** No. There are 2 vectors created. This time they may have their elements have consecutive addresses on the freestore however there is no guarantee that this will happen again. I am not even sure this happened perhaps there was a random 6 in the memory before the 1 vector. – drescherjm Nov 23 '16 at 02:40
  • *Based on the above experiment* -- And when you change compiler or compiler options, you may find that things are totally different. Also, when I run your code under Visual C++ debug runtime, I get a horrible message box that the index is out of bounds, not `6`. – PaulMcKenzie Nov 23 '16 at 02:43

0 Answers0