-2

I have used a vector as: vector<int> v(2)

Now I have pushed digit 1 to the vector.

Now when I will try to print the elements of v then the output will be as 0 0 1 Why the leading 2 zeroes are coming although I have not pushed them to the vector?

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Because you've created a vector of size `2` and so the elements will contain value `0`. Show us the code as [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Jason Aug 12 '22 at 12:28
  • Do you know what the `2` means in `vector v(2)`? Do you know how to find out? Do you know how your program behaves when you change that number? – Drew Dormann Aug 12 '22 at 12:28
  • This is explained in any beginner level [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Jason Aug 12 '22 at 12:34
  • See [What is `vector v(N)`](https://stackoverflow.com/questions/35478657/what-is-difference-between-vectorint-vn-and-vector-int-v-n) – Jason Aug 12 '22 at 12:36

1 Answers1

1

The two zeroes are there, because you created a vector with two zeroes. You could overwrite them, but push_back adds another value instead of overwriting existing elements.

MSalters
  • 173,980
  • 10
  • 155
  • 350