問題描述
這篇文章的評論部分有一個(gè)關(guān)于使用 std::vector::reserve 的帖子()
vs. std::vector::resize()
.
There is a thread in the comments section in this post about using std::vector::reserve()
vs. std::vector::resize()
.
這是原始代碼:
void MyClass::my_method()
{
my_member.reserve(n_dim);
for(int k = 0 ; k < n_dim ; k++ )
my_member[k] = k ;
}
我認(rèn)為要在vector
中寫入元素,正確的做法是調(diào)用std::vector::resize()
,不是 std::vector::reserve()
.
I believe that to write elements in the vector
, the correct thing to do is to call std::vector::resize()
, not std::vector::reserve()
.
事實(shí)上,以下測試代碼在 VS2010 SP1 的調(diào)試版本中崩潰":
In fact, the following test code "crashes" in debug builds in VS2010 SP1:
#include <vector>
using namespace std;
int main()
{
vector<int> v;
v.reserve(10);
v[5] = 2;
return 0;
}
我是對的,還是錯(cuò)的?VS2010 SP1 是對的,還是錯(cuò)的?
Am I right, or am I wrong? And is VS2010 SP1 right, or is it wrong?
推薦答案
有兩種不同的方法是有原因的:
There are two different methods for a reason:
std::vector::reserve
將分配內(nèi)存但不會(huì)調(diào)整向量的大小,向量的邏輯大小與之前相同.
std::vector::reserve
will allocate the memory but will not resize your vector, which will have a logical size the same as it was before.
std::vector::resize
實(shí)際上會(huì)修改向量的大小,并會(huì)用處于默認(rèn)狀態(tài)的對象填充任何空間.如果它們是整數(shù),則它們都為零.
std::vector::resize
will actually modify the size of your vector and will fill any space with objects in their default state. If they are ints, they will all be zero.
reserve 之后,在你的情況下,你需要很多 push_backs 來寫入元素 5.如果您不想這樣做,那么在您的情況下,您應(yīng)該使用調(diào)整大小.
After reserve, in your case, you will need a lot of push_backs to write to element 5. If you don't wish to do that then in your case you should use resize.
關(guān)于保留的一件事:如果您隨后使用 push_back 添加元素,直到達(dá)到您保留的容量,任何現(xiàn)有的引用、迭代器或指向向量中數(shù)據(jù)的指針都將保持有效.所以如果我保留 1000 并且我的大小是 5,&vec[4]
將保持不變,直到向量有 1000 個(gè)元素.之后,我可以調(diào)用 push_back()
并且它會(huì)工作,但是之前存儲的 &vec[4]
指針可能不再有效.
One thing about reserve: if you then add elements with push_back, until you reach the capacity you have reserved, any existing references, iterators or pointers to data in your vector will remain valid. So if I reserve 1000 and my size is 5, the &vec[4]
will remain the same until the vector has 1000 elements. After that, I can call push_back()
and it will work, but the stored pointer of &vec[4]
earlier may no longer be valid.
這篇關(guān)于std::vector::resize() 與 std::vector::reserve()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!