Resize Std Vector

I have std :: vector and I have to resize it with some default value. Here is the code:

static int Counter = 0; class Data { /* ... */ Data() { Counter++; std::cout << Counter << std::endl; } }; std::vector<Data> mArray; for (int i=0; i <= 200; ++i) { mArray.push_back(Data()); } // And resizing somewhere: std::cout << "Resizing!\n"; mArray.resize(400, Data()); 

As I understand it, after inserting 200 elements, I can resize it using the resize function, which takes a new size and default value for each new element.

When I run this program, I see:

 0 1 2 ... 199 200 Resizing 201 

Why is there only 1 element after the change?

+4
source share
5 answers

You see only the invoice from your default constructor when the added entries are copied. You will need to add a copy constructor that also takes copies into account:

  Data(const Data& other) { // Actual copying code, whatever that may be Counter++; std::cout << Counter << std::endl; } 
+12
source

Since the default constructor is called once: std :: vector copies its contents, so you actually copy the same object 200 times.

+5
source

Because resize will use the copy constructor to insert new elements, and for this reason, the default constructor is called only once.

+3
source

Since other instances of 199 instances are created by copying the Data instance that you pass in to resize () through its copy constructor.

+2
source

You print Counter++ , not the size of your vector (since only 1 Data object is created to initialize the rest of the object, it only increases once).

+2
source

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


All Articles