C++ 模板化类的动态数组(即向量)
C++ Dynamic arrays of templated classes (i.e. vector)
我目前正在自学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));
它会分配内存,但不会创建对象,因为它不会调用其构造函数。
相关文章:
- 将数组/向量发送到 c++ 脚本的 cython 示例
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 将指向多维数组向量中的单个项的指针传递给函数 c++
- 数组向量的文件 I/O
- 在一行中初始化和引入数组向量的正确方法?
- C++ 返回具有最小硬币的数组/向量以获得价值动态规划
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- (C )创建可以从功能访问的动态全局数组/向量
- 提升是否具有用于数组向量的智能指针
- 将函数应用于数组向量的元素
- 数组向量的内存布局是什么
- 获取数组/向量末尾地址的未定义行为
- "Empty"数组\向量成员 C++
- 将字符串向量转换为双2-D数组向量
- 排序多维数组/向量
- 如何创建模板化对象的数组/向量
- 如何在数组向量上使用 std::find
- 无法删除C++中的数组/向量
- 具有元素自定义构造函数的对象数组/向量