Are vectors resized?

I am very sorry to ask such a beginner question, but I find conflicting information on the Internet. I would ask the university, but it comes out only in February next year.

Will vectors really resize? Or you need to periodically check the current size and resize when you need more space. It will automatically change for me, but I'm not sure if this is a function or the compiler is waving a magic wand.

+6
source share
2 answers

If you use push_back or insert , yes, the vector resizes. 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 outputs as:

 1 2 3 Current size 3 

Now remember, if you do a[3] = 5 . It will not resize your vector automatically.
You can also manually resize the vector if you want. To demonstrate, add the following code to the code above.

 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 

I think you got your answer.

+11
source

Do vectors automatically resize?

Yes, they do it, and you can easily verify this:

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

Source: https://habr.com/ru/post/978775/


All Articles