所以我有一个 vector ,它最初是空的,但肯定会被填满。它包含结构实例:
struct some {
int number;
MyClass classInstance;
}
/*Meanwhile later in the code:*/
vector<some> my_list;
当它发生时,我想给 vector 增加值,我需要将它放大一倍。但当然,我不想为此创建任何变量。如果没有这个要求,我会这样做:
//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!
因此,我想通过增加 vector 的大小在 vector 中创建 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
但这行不通!似乎没有分配空间 - 我得到了 vector subscript out of range 错误。
最佳答案
my_list.reserve(index+1); // size() remains the same
保留不会更改 my_list.size()
。它只是增加了容量。您将此与 resize
混淆了:
my_list.resize(index+1); // increase size by one
另见 Choice between vector::resize() and vector::reserve() .
但我推荐另一种方式:
my_vector.push_back(some());
额外的拷贝将从您的编译器中删除,因此没有开销。如果你有 C++11,你可以通过嵌入 vector 来更优雅地做到这一点。
my_vector.emplace_back();
关于c++ - 在 vector 中创建新的空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466860/