Tom*_*ica 1 c++ memory-management stdvector
所以我有一个向量,初始是空的,但肯定会被填满.它包含结构实例:
struct some {
int number;
MyClass classInstance;
}
/*Meanwhile later in the code:*/
vector<some> my_list;
Run Code Online (Sandbox Code Playgroud)
当它发生时,我想为向量添加值,我需要将其放大一个.但是,当然,我不想创建任何变量来做到这一点.没有这个请求,我会这样做:
//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!
Run Code Online (Sandbox Code Playgroud)
所以,相反,我想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
Run Code Online (Sandbox Code Playgroud)
但这不起作用!似乎空间没有分配 - 我得到矢量下标超出范围错误.
my_list.reserve(index+1); // size() remains the same
Run Code Online (Sandbox Code Playgroud)
储备不会改变my_list.size().它只是增加了容量.你有点困惑resize:
my_list.resize(index+1); // increase size by one
Run Code Online (Sandbox Code Playgroud)
另请参见vector :: resize()和vector :: reserve()之间的选择 .
但我推荐另一种方式:
my_vector.push_back(some());
Run Code Online (Sandbox Code Playgroud)
附加副本将从编译器中删除,因此没有开销.如果你有C++ 11,你可以通过插入向量来实现更优雅.
my_vector.emplace_back();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1010 次 |
| 最近记录: |