Using reserve()
followed by push_back()
's may be faster than resizing the vector and later performing assignments -- as seen in std::vector reserve() and push_back() is faster than resize() and array index, why?.
However, if I make assignments instead of using push_back()
, the size of the vector remains 0
:
# include <vector>
int main() {
std::vector<int> x;
x.reserve(10);
x[0] = 10, x[1] = 9, x[2] = 8, x[3] = 7, x[4] = 6;
x[5] = 5, x[6] = 4, x[7] = 3, x[8] = 2, x[9] = 1;
std::cout << x[2] << std::endl;
std::cout << "SIZE: " << x.size() << std::endl; // 'size()' is 0
x.resize(10); // removes former entries, since the vector had 'size() = 0'
std::cout << x[2] << std::endl;
std::cout << "SIZE: " << x.size() << std::endl; // 'size()' is 10,
// but values are gone
}
Output:
8
SIZE: 0
0
SIZE: 10
How could I change the size of a vector, without destroying reserved entries? Of course, I still want to use reserve()
, to reduce the cost of allocations -- I know the exact size I need.