在矢量中创建新的空字段

Create new empty field in vector

本文关键字:字段 创建      更新时间:2023-10-16

所以我有一个向量,它最初是空的,但肯定会被填满。它包含结构实例:

struct some {
    int number;
    MyClass classInstance;
}
/*Meanwhile later in the code:*/
vector<some> my_list;

当它发生时,我想把值加到向量上,我需要把它放大一。但当然,我不想创建任何变量来做这件事。如果没有这个要求,我会这样做:

//Adding new value:
some new_item;       //Declaring new variable - stupid, ain't it?
my_list.push_back(new_item); //Copying the variable to vector, now I have it twice!

因此,相反,我想通过增加向量的大小来在向量中创建new_item——看看:

int index = my_list.size();
my_list.reserve(index+1);  //increase the size to current size+1 - that means increase by 1
my_list[index].number = 3;  //If the size was increased, index now contains offset of last item

但这行不通!似乎没有分配空间,我得到了向量下标超出范围的错误。

my_list.reserve(index+1); // size() remains the same 

保留不更改my_list.size()。它只是增加了容量。您将此与resize:混淆

my_list.resize(index+1);  // increase size by one

另请参见在vector::resize((和vector::reserve((之间进行选择。

但我推荐另一种方式:

my_vector.push_back(some());

额外的副本将从编译器中删除,因此没有开销。如果您有C++11,您可以通过将其放置到向量中来实现这一点。

my_vector.emplace_back();

std::vector::reserve只确保分配了足够的内存,不会增加vector的大小。您正在查找std::vector::resize

此外,如果您有C++11编译器,则可以使用std::vector::emplace_back在适当的位置构建新项,从而避免复制。

my_list.emplace_back(42, ... ); // ... indicates args for MyClass constructor

reserve()只是向分配器请求空间,但实际上并没有填充。请尝试vector.resize()