Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Vectors resize automatically?

Tags:

c++

vector

I am very sorry that I am asking such a beginner question but I am finding contradictory information online. I would ask at University but it is out until February next year.

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.

like image 570
Lord Windy Avatar asked Nov 27 '14 05:11

Lord Windy


People also ask

How do vectors change size?

Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container's content in actual by inserting or deleting the elements from it.

Does vector resize after erase?

Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

Can vectors shrink?

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

How do you resize vector vectors?

resize(COL, vector<char>(ROW)); Alternatively, when initializing or if you want to reset a non-empty vector, you can use the constructor overload taking a size and initial value to initialize all the inner vectors: matrix = vector<vector<char> >(COL, vector<char>(ROW));


1 Answers

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 << a << " ";
}
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

It think you got your answer.

like image 139
Ashwani Avatar answered Oct 26 '22 18:10

Ashwani