I am trying to fix some code that uses vectors a lot and there are some loops that look like this:
for (int t=0;t<T;t++){ std::vector<double> vect; for (int i=0;i<MAX;i++){ double value; vect.push_back(value); } /*....*/ }
I know more or less how to improve this by reusing the same vector for the outer iterations, but while doing this I found that when calling std::vector::clear
"the vector capacity is not guaranteed to change", while I was actually hoping that the capacity would be guaranteed to not change. Maybe I am just misunderstanding what is written on cplusplus.com. However, my question is:
How can I clear a vector without changing its capacity?
Should I call reserve
after clear
to make sure the capacity will be the same?
PS: just to be clear, I want to rewrite above code to
std::vector<double> vect; vect.reserve(MAX); for (int t=0;t<T;t++){ for (int i=0;i<MAX;i++){ double value; vect.push_back(value); } /*....*/ vect.clear(); }
ie. I still want to fill it via push_back
and I am worried about the clear()
changing the capacity of the vector.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
Yes, size is decreased as you erase elements. Returns the number of elements in the vector.
C++ Vector Library - reserve() FunctionThe C++ function std::vector::reserve() requests to reserve vector capacity be at least enough to contain n elements. Reallocation happens if there is need of more space.
Using vector::clear function So, we're left with a vector of size 0 but some finite capacity. Starting with C++11, we can call the vector::shrink_to_fit function after clear() , which reduces the vector's capacity to fir the size. It works by “requesting” a reallocation on the vector.
cppreference said explicitly that the capacity of the vector is unchanged.
from cppreference (bold emphases it is own me):
void clear();
Removes all elements from the container. Invalidates any references, pointers, or iterators referring to contained elements. May invalidate any past-the-end iterators.
Leaves the capacity() of the vector unchanged.
EDIT
As pointed out by Dmitry Kuznetsov in the comment, the standard does not mention the capacity:
expression:
a.clear()
return type:
void
Assertion/note pre-/post-condition: Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.post: a.empty() returns true.
Complexity: Linear.
Yes, call reserve()
after clear()
. In the worst case, you'll have a single deallocation/allocation taking place, which would have negligible impact in case of a vector of PODs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With