标准向量调整大小
我有一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当添加的条目是复制构造的时,您只能看到来自默认构造函数的计数。您还必须添加一个复制构造函数来计算副本:
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:
因为默认构造函数被调用一次: 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.
因为 resize 将使用复制构造函数来插入新元素,因此默认构造函数仅被调用一次。
Because resize will use the copy constructor to insert new elements and for this reason, the default constructor is called only once.
因为其他 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.
您正在打印
Counter++
,而不是向量的大小(因为仅创建 1 个Data
对象来初始化向量的其余部分,因此它只会递增一次)。You are printing out
Counter++
, not the size of your vector (since only 1Data
object is created to initialize the rest of the vector, it only gets incremented once).