-1

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?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

2 Answers2

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
  • 4
    Note 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