Lord Windy
Lord Windy

Reputation: 792

Do Vectors resize automatically?

Do Vectors resize automatically? Or do you need to check the current size periodically and resize when you need more room?

It looks to be resizing for me automatically but I'm not sure if that is a feature or the compiler waving a magic wand.

Upvotes: 8

Views: 17702

Answers (2)

Ashwani
Ashwani

Reputation: 2052

If you use push_back or insert, yes vector resizes itself. Here is a demo:

#include<iostream>
#include<vector>

using namespace std;

int main() {
    vector < int > a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    for (int value : a) {
        cout << value << " ";
    }
    cout << endl << "Current size: " << a.size() << endl;
    return 0;
}

It gives output as:

1 2 3
Current size: 3

Remember now if you do a[3] = 5. It will not resize your vector automatically.
Also you can manually resize vector if you want. For demo append following code to above code.

a.resize(6);
for (int value : a) {
    cout << value << " ";
}
cout << endl << "Current size: " << a.size() << endl;

Now it will output:

1 2 3
Current size: 3
1 2 3 0 0 0
Current size: 6

I think you got your answer.

Upvotes: 14

fredoverflow
fredoverflow

Reputation: 263128

Do Vectors resize automatically?

Yes, they do, and you can convince yourself of that very easily:

std::vector<int> squares;
for (int i = 0; i < 100; ++i)
{
    squares.push_back(i * i);
    std::cout << "size: " << squares.size() << "\n";
}

Upvotes: 4

Related Questions