在矢量中创建新的空字段
Create new empty field in vector
所以我有一个向量,它最初是空的,但肯定会被填满。它包含结构实例:
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
但这行不通!似乎没有分配空间,我得到了向量下标超出范围的错误。
my_list.reserve(index+1); // size() remains the same
保留不更改my_list.size()
。它只是增加了容量。您将此与resize
:混淆
my_list.resize(index+1); // increase size by one
另请参见在vector::resize((和vector::reserve((之间进行选择。
但我推荐另一种方式:
my_vector.push_back(some());
额外的副本将从编译器中删除,因此没有开销。如果您有C++11,您可以通过将其放置到向量中来实现这一点。
my_vector.emplace_back();
std::vector::reserve
只确保分配了足够的内存,不会增加vector
的大小。您正在查找std::vector::resize
。
此外,如果您有C++11编译器,则可以使用std::vector::emplace_back
在适当的位置构建新项,从而避免复制。
my_list.emplace_back(42, ... ); // ... indicates args for MyClass constructor
reserve()
只是向分配器请求空间,但实际上并没有填充。请尝试vector.resize()
相关文章:
- 创建 10x10 的按钮字段
- 如何创建一个函数来提取向量内部字符串中的字段?
- 用于基于成员字段或函数创建比较器的快捷方式
- C++创建一个链表,每个节点有超过 2 个字段
- C MPI创建并发送具有字段char [16]和整数的结构数组
- 安全的方法来为char []字段创建Getter
- 如何为我的 Vulkan 类创建此通用数据结构字段
- C++ 如何创建位图字段
- 在抽象类中,可以使用抽象类A的类型创建一个静态字段
- 如何创建具有4个字段和每个字段9个字符长度的矢量对象
- 当您有结构名称和字段值的列表时,是否可以以编程方式创建结构的对象并填充字段
- 如何在容器项的字段上创建迭代器?
- 剪辑在 c++ 中创建多字段
- 在 Qt 创建器中禁用 -wmissing 字段初始值设定项警告
- C++ 如何在结构向量的一个字段上创建迭代器
- 如何创建一个包含用户在程序中输入的 3 个字段的结构
- ADO 创建参数在尝试从 C++ 写入 Oracle 的 RAW(16) 字段时失败并出现0x800A0D5D
- 原始数据包创建导致 IP 字段顺序不正确
- 在Visual c++ 2010中不能使用default_random_engine字段创建类
- C++-有没有一种方法可以为字段创建别名