Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Std vector resizing

I have some 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, after inserting 200 items, I can resize it with resize function which takes new size and default value for each new element.

When I run that program I see:

0
1
2
...
199
200
Resizing
201

Why does only 1 item is inserted after resizing?

like image 460
Max Frai Avatar asked Nov 29 '22 10:11

Max Frai


1 Answers

You're only seeing a count from your default constructor, when the entries being added are copy constructed. You'll have to add a copy constructor that counts copies as well:

   Data(const Data& other) { 
      // Actual copying code, whatever that may be
      Counter++; 
      std::cout << Counter << std::endl;
   }
like image 143
Fred Larson Avatar answered Dec 08 '22 21:12

Fred Larson