如何在C++中使用"new"动态分配向量数组?
How do I dynamically allocate an array of vectors using "new" in C++?
这是针对哈希表实验室的,所以我需要能够向向量添加条目。另外,我将如何访问具有这种格式的条目?
与
动态分配其他任何内容的数组的方式相同:
std::vector<T>* array = new std::vector<T>[42];
尽管仅使用 vector
s 的vector
要简单得多:
std::vector<std::vector<T> > array(42);
数组可以像 Barry 提到的那样创建。您可以通过与任何其他信息相同的方式访问信息:
std::vector<int>* numbers = new std::vector<int>[5]; // 5 vectors of ints
// iterate through all elements
for (int i = 0; i < 5; ++i)
{
numbers[i].push_back(i * 2);
cout << numbers[i][0] << endl;
// * ^
// * = array index
// ^ = vector index
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 在c++中,在new(动态分配)之前使用星号(*)
- 如何在C++中使用"new"动态分配向量数组?
- 在C++中使用带有二进制搜索的new动态内存分配
- 在动态分配中,在关键字new之前使用Why(unsigned char*)
- 在C++中,如何在没有动态分配(即NEW)的情况下将对象初始化为对象内部的指针
- 当我们可以使用=运算符为字符串赋值时,为什么要在赋值之前使用new运算符为字符串动态分配内存
- 如何在c++中使用new为类动态分配内存
- 内存管理:使用new操作符进行数组和动态分配
- 在c++中由new和delete动态分配
- 从指针向量中删除元素,并释放先前通过new操作符分配的动态内存