user1673206
user1673206

Reputation: 1711

Using the same vector without the resize() part

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.

Upvotes: 1

Views: 81

Answers (1)

bolov
bolov

Reputation: 75924

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.

Upvotes: 3

Related Questions