Interviewer asked this question to me in one of my interview. I think that there is no way to clear the capacity of the vector. Can anyone confirm on this?
Asked
Active
Viewed 131 times
-1
-
https://stackoverflow.com/questions/2628345/will-a-call-to-stdvectorclear-set-stdvectorcapacity-to-zero – Oshada Oct 05 '18 at 08:25
-
1What did the interviewer *mean* by "clear the capacity"? Perhaps all you need is to study [a `std::vector` reference](https://en.cppreference.com/w/cpp/container/vector)? – Some programmer dude Oct 05 '18 at 08:25
-
3There's `shrink_to_fit` method which may or may not do anything. There's no guarantee. If it works, it does clear the capacity. – n. m. could be an AI Oct 05 '18 at 08:29
-
You can just re-initialise the vector. `vector
a={1,2,3,4};` `a=vector – maigar Oct 05 '18 at 08:31();`
2 Answers
5
You would need shrink_to_fit
Although it doesn't guarantee that the call would be honored.
Requests the removal of unused capacity.
It is a non-binding request to reduce capacity() to size(). It depends on the implementation whether the request is fulfilled.
This code may or may not work depending on implementation (although would work on most implementations)
template<typename T>
void ClearCapacityPleaseIfYouCan(std::vector<T> &v){
v.resize(0);
v.shrink_to_fit();
}
std::vector
tries to hide away abstraction of storage from you. For most use cases you don't need to know how the capacity is growing or shrinking. But then interviewers have been known to not give damn to real use cases.

bashrc
- 4,725
- 1
- 22
- 49
0
There is a way: swap with an empty vector.
std::vector<T> vec_to_clear;
....
{
std::vector<T> empty;
std::swap(vec_to_clear, empty);
}

Evg
- 25,259
- 5
- 41
- 83
-
4Note that an empty vector is not guranteed by standard to start with a capacity of 0. Most implementations would start at 0 though. – bashrc Oct 05 '18 at 08:50
-
@bashrc, interesting point, thanks. Is possible non-zero initial capacity specified in the Standard explicitly, or is it a consequence of no such specification? – Evg Oct 05 '18 at 08:57