标准向量调整大小

发布于 2024-10-10 04:39:12 字数 590 浏览 0 评论 0原文

我有一些 std::vector ,我必须使用一些默认值调整它的大小。这是代码:

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());

据我了解,插入 200 个项目后,我可以使用 resize 函数调整其大小,该函数为每个新元素采用新的大小和默认值。

当我运行该程序时,我看到:

0
1
2
...
199
200
Resizing
201

为什么调整大小后仅插入 1 个项目?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

挽你眉间 2024-10-17 04:39:12

当添加的条目是复制构造的时,您只能看到来自默认构造函数的计数。您还必须添加一个复制构造函数来计算副本:

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

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;
   }
不羁少年 2024-10-17 04:39:12

因为默认构造函数被调用一次: std::vector 复制其内容,所以您实际上复制了同一个对象 200 次。

Because the default constructor is called once: std::vector copies its contents, so you're actually copying the same object 200 times.

森林迷了鹿 2024-10-17 04:39:12

因为 resize 将使用复制构造函数来插入新元素,因此默认构造函数仅被调用一次。

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

ˇ宁静的妩媚 2024-10-17 04:39:12

因为其他 199 个 Data 实例是通过复制您通过其复制构造函数传递给 resize() 的 Data 实例来创建的。

Because the other 199 Data instances are created by copying the Data instance that you pass to resize() via its copy constructor.

执笏见 2024-10-17 04:39:12

您正在打印 Counter++,而不是向量的大小(因为仅创建 1 个 Data 对象来初始化向量的其余部分,因此它只会递增一次)。

You are printing out Counter++, not the size of your vector (since only 1 Data object is created to initialize the rest of the vector, it only gets incremented once).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文