所以我有一个向量,最初是空的,但肯定会被填满。它包含结构的实例:
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
但这不起作用!似乎没有分配空间 - 我得到向量下标超出范围错误。