vector converted all negative value to zero

  • A+
Category:Languages

I made a vector of constant size to store negative values, and then printing the values all I got was zeroes. I just want to know why it is not storing negative values.

vector<int> v(5); v.push_back(-1); v.push_back(-2); v.push_back(-3); v.push_back(-4); v.push_back(-5);  for(int i=0;i<5;i++) cout<<v[i]<<" ";  //all i got zeroes 

 


That's because push_back puts new elements onto the end of the vector.

You can see the effect by running i to 9: the negative numbers will occupy v[5] to v[9].

Writing

std::vector<int> v{-1, -2, -3, -4, -5}; 

instead is a particularly elegant fix.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: