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.
More Related Contents:
- Looking for C++ STL-like vector class but using stack storage
- Vectors, structs and std::find
- iterate vector, remove certain items as I go
- Array of vectors
- How do I print out the contents of a vector?
- Are std::vector elements guaranteed to be contiguous?
- vector vs. list in STL
- How do I sort a std::vector by the values of a different std::vector?
- Is it safe to assume that STL vector storage is always contiguous?
- Efficient way of reading a file into an std::vector?
- How to use an iterator?
- How to initialize std::vector from C-style array?
- What is the best way to concatenate two vectors?
- Iterating C++ vector from the end to the beginning
- Is it safe to push_back an element from the same vector?
- How to store extremely large numbers?
- Moving elements from std::vector to another one
- Performance issue for vector::size() in a loop in C++
- STL vector and thread-safety
- How do you copy the contents of an array to a std::vector in C++ without looping?
- what is “stack alignment”?
- VBOs with std::vector
- Why would I prefer using vector to deque
- What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?
- What is the size of sizeof(vector)? C++
- TMP: how to generalize a Cartesian Product of Vectors?
- std::vector removing elements which fulfill some conditions
- Howto create combinations of several vectors without hardcoding loops in C++?
- Why don’t std::vector’s elements need a default constructor?
- What happen to pointers when vectors need more memory and realocate memory?