C++ 模板化类的动态数组(即向量)

C++ Dynamic arrays of templated classes (i.e. vector)

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

我目前正在自学C++并尝试实现一个简单的哈希图(有两个模板类)。

但是,我不知道如何正确初始化矢量的动态数组。我失败的尝试:

std::vector<Key> *keys = new std::vector<Key>[size];
std::vector<Key> *keys = (std::vector<Key> *) malloc(sizeof(std::vector<Key>) * size);
std::vector<Key> **keys = reinterpret_cast<vector<Key> **>(malloc(sizeof(vector<Key>) * size));

还是我在别的地方做错了什么?:(

您正在执行的操作是不必要的,矢量支持动态大小调整,您无需new它。

所以:

std::vector<Key> keys = std::vector<Key>(size); // is fine to initialise the vector to a specific size.

如果你想有一个指向向量的指针,那么你可以像这样新

std::vector<Key>* keys = new std::vector<Key>(size);

此外,您可以随时根据需要添加和删除元素,如有必要,它将调整大小,或者您可以强制它:

keys.resize(newSize); // note that if the new size is larger than current size
// it will default fill the new elements so if your `vector` is of `ints` 
// then it will pad with zeros.

你应该这样做:

std::vector<Key> *keys = new std::vector<Key>(size);

即使其中一次尝试奏效了:

std::vector<Key> *keys = (std::vector<Key> *) malloc(sizeof(std::vector<Key>) * size);
std::vector<Key> **keys = reinterpret_cast<vector<Key> **>(malloc(sizeof(vector<Key>) * size));

它会分配内存,但不会创建对象,因为它不会调用其构造函数。