c++ - vector push_back zero into an empty vector -


I had encountered the following property of std :: vector which I did not know and I Wondering if someone could make it clear to me.

I think this code:

  int main () {int i = 5; Of vector & lt; Int & gt; Vector; While (i & gt; 0) {vector.push_back (i); - I }}  

A vector should be created with the following elements:

  5, 4, 3, 2, 1  

However, when I get the code, I run it over:

  5, 4, 3, 2, 0  

Going on to find out I have printed the vector at each stage and I get the following sequence:

  • i = 5 - vector (0)
  • i =
  • i = 2 - vector (5, 4, 3, 0)
  • i = 3 - vector (5, 4, 0)
  • Li>
  • i = 1 - vector (5, 4, 3, 2, 0)

this A. I think that in some way the first cycle becomes zero (where should be 5) which is very strange if I say a big (n = 10) then the cycle is revised every time the last time.

I do not understand what is happening, my guess is that there is something in buffer that takes you back before 5 and then it takes the push back and goes out of the cycle. Or is it something else?


EDIT:


So people informed with care - or contained - the error in the comments was in accordance with the printing rule which I was used to. It was for the record:

  zero print_vector (std :: vector & gt; int & gt; vector) {cout & lt; & Lt; String (10, '-') & lt; & Lt; Endl; Cout & lt; & Lt; For "("; (int i = 0; i & lt; vector.size () - 1; ++ i) {cout  ; } Cout & lt; vector [vector. Size] COAT & lt; ")" & lt; & Lt; Endl; }  

and make mistakes vector [vector. ()] which are weird stuff when there are no elements in the vector that I think.

Yes, your error is actually in the print code

  vector [Vector.size ()]  

Expression is invalid in C ++ in vector [0; The element in the vector.size () ) category, and attempts to reach a non-existent expression is the one-last-element element of the vector, which is an undefined behavior.


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -