cpp_noname
cpp_noname

Reputation: 2071

Unexpected results when calling resize() on an STL vector in C++

In the following code, if I call v.resize(n), the program will print out 0 0 0 0 0 0 0 0 0 0, which is not what I wanted to see. However, if I comment the line containing v.resize(n) out, it will print out 0 1 2 3 4 5 6 7 8 9, which is what I wanted to see. Why is this the case? What's wrong with my logic here?

#include <iostream>
#include <vector>

using namespace std;

int main( int argc , char ** argv )
{
    int n = 10;
    vector<int> v;
    v.resize(n);

    for( int i=0 ; i<n ; i++ )
    {
        v.push_back(i);
    }

    for( int i=0 ; i<n ; i++ )
    {
        cout << v[i] << " ";
    }

    cout << endl;

    return 0;
}

Upvotes: 1

Views: 148

Answers (3)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

vector.resize()

Resizes the container so that it contains n elements.

You're resizing it to n (10). So now it has ten 0's in it. Then you add ten more numbers (0 to 9) to the end of the list (via push_back()). Finally, you print out only the first n (10) which are still all zero.

Your program is doing exactly what you're telling it to do.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234655

v.push_back(i) increases the size of the vector v by 1 with i being the value of the last element in that vector. That is why the 10 zeros are retained at the start (i.e. front) of the vector.

You should write v[i] = i instead.

Whatever you do, don't drop the line v.resize(n); and retain your push_back as it's suboptimal to piecewise resize a vector - due to memory reallocation. (Although a good stl will have optimisations for such programming it's good practice not to rely on that).

Upvotes: 5

Marcin Łoś
Marcin Łoś

Reputation: 3246

resize ensures the vector contains exactly n elements, while push_back appends items to the vector, so the nubmers are added after zeros that occupy the vector after resizing. You can see it if you print all the numbers in the vector (< v.size()) instead of just first n.

Method that behaves as you seem to have expected is reserve():

Effects: A directive that informs a vector of a planned change in size, so that it can manage the storage allocation accordingly. After reserve(), capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve(). If an exception is thrown other than by the move constructor of a non-CopyInsertable type, there are no effects. (§23.3.6.3/2)

Upvotes: 7

Related Questions