I encountered the following property of std::vector
that I did not know and I was wondering if someone could clarify it for me.
I think this code:
int main()
{
int i = 5;
vector<int> vector;
while(i > 0){
vector.push_back(i);
--i;
}
}
should produce a vector with the following elements:
5, 4, 3, 2, 1
However, when I run the code above what I get is:
5, 4, 3, 2, 0
In order to explore what is going on I printed the vector at each stage and I get the following sequence:
So I think somehow a zero gets push_backed in the first cycle (where 5 should be) which is very strange. If I try a bigger (say n=10) then the last element is modified every time cycle.
I do not understand what's going. My guess is that there is something in the buffer maybe that get's push back before 5 and then this puts the push back and the cycle out of phase. Or is it something else?
Edit:
So as people kindly pointed out -or implied- in the comments the error was in the printing routine that I was used. For the record it was:
void print_vector(std::vector<int> vector){
cout << string(10, '-') << endl;
cout << "(";
for(int i=0; i < vector.size() - 1; ++i){
cout << vector[i] << ", ";
}
cout << vector[vector.size()];
cout << ")" << endl;
}
And the mistakes comes from the vector[vector.size()]
which does weird things when the vector does not have elements I guess.
Yes, your error is indeed in the printing code. The
vector[vector.size()]
expression is illegal in C++. Vector contains elements in range [0;vector.size()
), and the expression tries to access the non-existent. one-past-end element of the vector, which is undefined behavior.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments