如何在C++中使用"new"动态分配向量数组?

How do I dynamically allocate an array of vectors using "new" in C++?

本文关键字:new 动态分配 数组 向量 C++      更新时间:2023-10-16

这是针对哈希表实验室的,所以我需要能够向向量添加条目。另外,我将如何访问具有这种格式的条目?

动态分配其他任何内容的数组的方式相同:

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
}