2013-03-17 75 views
1

所以我有一個向量,它初始爲空,但肯定沒有填充。它包含結構的實例:在向量中創建新的空場

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! 

所以,相反,我希望通過增加它的大小來創建矢量內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 

但這並不工作!似乎空間沒有分配 - 我得到矢量下標超出範圍錯誤。

回答

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(); 
+0

我非常小心使用'new'。我應該同時調用'.reserve'(分配)和'.resize'(調整大小)嗎? – 2013-03-17 22:18:07

+0

只有在向量中插入許多值時才使用保留。 'resize'非常聰明,並且通過一個常數因子(通常爲2)來提供容量,以便在分攤的恆定時間內提供'push_back'。 – ipc 2013-03-17 22:20:01

2

std::vector::reserve只有確保足夠的內存分配,它不會增加vector的大小。您正在尋找std::vector::resize。另外,如果您有一個C++ 11編譯器,則可以使用std::vector::emplace_back來構建新的項目,從而避免複製。

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

reserve()只是要求空間的分配,但實際上不填充它。嘗試vector.resize()