c++ - 在 vector 中创建新的空字段

标签 c++ memory-management stdvector

所以我有一个 vector ,它最初是空的,但肯定会被填满。它包含结构实例:

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!

因此,我想通过增加 vector 的大小在 vector 中创建 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

但这行不通!似乎没有分配空间 - 我得到了 vector subscript out of range 错误。

最佳答案

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,你可以通过嵌入 vector 来更优雅地做到这一点。

my_vector.emplace_back();

关于c++ - 在 vector 中创建新的空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466860/

相关文章:

c++ - 如何在 linux 上获取在 "black box"中创建的线程数?

c++ - 编译器内存优化 - 重用现有 block

java - OutOfMemoryError - 我可以将数据转储到文件而不是内存中吗?

c++ - 如何有效地格式化从 std::vector 到 std::string 的值?

c++ - 在 'Other user' 磁贴上显示 V2 凭据提供程序

c++ - 在子函数中分配 CFString

c - 垃圾收集器会在这里做什么?

c++ - 什么情况下 std::vector.clear() 会调用析构函数?

c++ - 从多个 std::vectors 中删除项目的最快方法

c++ - 考虑STL容器操作的复杂性