所以我有一个向量,它最初是空的,但肯定会被填满。它包含结构实例:
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
但这不起作用!似乎没有分配空间 - 我得到向量下标超出范围错误。
答案 0 :(得分:5)
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,你可以通过插入向量来实现更优雅。
my_vector.emplace_back();
答案 1 :(得分:2)
std::vector::reserve
只能确保分配足够的内存,但不会增加vector
的大小。您正在寻找std::vector::resize
。
此外,如果你有一个C ++ 11编译器,你可以使用std::vector::emplace_back
来构建新项目,从而避免复制。
my_list.emplace_back(42, ... ); // ... indicates args for MyClass constructor
答案 2 :(得分:0)
reserve()
只是询问空间的分配器,但实际上并没有填充它。试试vector.resize()