所以我有一個向量,它初始爲空,但肯定沒有填充。它包含結構的實例:在向量中創建新的空場
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
但這並不工作!似乎空間沒有分配 - 我得到矢量下標超出範圍錯誤。
我非常小心使用'new'。我應該同時調用'.reserve'(分配)和'.resize'(調整大小)嗎? – 2013-03-17 22:18:07
只有在向量中插入許多值時才使用保留。 'resize'非常聰明,並且通過一個常數因子(通常爲2)來提供容量,以便在分攤的恆定時間內提供'push_back'。 – ipc 2013-03-17 22:20:01