1

I have a question about std::vector -

vector<int> vec(1,0);

while(//something_1)
{
    while(//something_2)
    {
       ...
       vec.pushback(var)
       ...
    }

    process(vec.size()); //every iteration- different size

    vec.clear();
    vec.resize(0,0);
}

On this case - every vec.push_back(var) there is reallocation of a new array with size bigger by one than the former array.

My question is - if there is a way using one vector, so after the inner while(//something_2), the vec.push_back(var) command will push back from the first cell of vec? instead of using vec.clear() and vec.resize(0,0)? so I could save the resize part and the reallocation.

The size of the vector is important for the function process(vec.size())

Thanks.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
user1673206
  • 1,671
  • 1
  • 23
  • 43
  • 7
    If that's the case, then your `vector` implementation is horribly broken. `push_back` should make it grow exponentially, and it shouldn't need to reallocate after `clear` until it grows beyond its capacity (which will be at least as large as the old size). How are you determining that it grows by one for each `push_back`? – Mike Seymour May 04 '15 at 06:30

1 Answers1

3

You can use reserve first time if you know beforehand approximately how much your vector could grow.

clear Leaves the capacity() of the vector unchanged. Which means that push_back & and other modifiers will use the same memory.

resize(0,0) should be removed.

bolov
  • 72,283
  • 15
  • 145
  • 224