Kiran
Kiran

Reputation: 5526

vector resize strange behavior

I have the following code. The interesting part is if I uncomment the resize() on vector, it is priting 10 numbers for an input value of 5. I am using eclipse with mingw and gcc on windows xp. Shouldn't the iterator go only for 5 elements?

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
//#include "stdio.h"
using namespace std;

template <typename T>
void print_coll(T t)
{
    typename T::iterator iter = t.begin();
    while (iter != t.end() )
    {
        cout << *iter << " ";
        ++iter;
    }
    cout << endl;
}

int main()
{
    int size;
    cin >> size;
    vector<int> numbers;
//    numbers.resize(size);

    for ( int i = 0 ; i < size; ++i ) {
        int r = (rand() % 10);
        numbers.push_back(r);
    }
    print_coll(numbers);

}

Upvotes: 2

Views: 658

Answers (2)

Erik
Erik

Reputation: 91270

numbers.resize(size);

This adds size 0's to the vector.

for ( int i = 0 ; i < size; ++i ) {
    int r = (rand() % 10);
    numbers.push_back(r);
}

And this adds size random values to the vector.

Likely you wanted reserve not resize. reserve does not change the "visible" size of the vector it only changes the internal size of the storage used by the vector, resize however changes the "visible" size.

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308121

resize resizes the vector, inserting default values for each of the items it needs to create for the new size. You want reserve.

Upvotes: 9

Related Questions