如何创建向量数组
How to create an array of vectors
如何正确初始化向量数组?
图.h
class Graph
{
public:
Graph(int vertices);
private:
vector<int> adjacencyLists[];
}
图形.cpp
Graph::Graph(int vertices)
{
adjacencyLists = new vector<int>[vertices];
}
错误:
error: incompatible types in assignment of 'std::vector<int>*' to 'std::vector<int> [0]'
adjacencyLists = new vector<int>[vertices];
^
对于您的用例(一个动态分配的数组,构造后无法更改大小)来说,完美的是std::dynarray
。可悲的是,这目前不在标准中。以下是它的工作原理:
dynarray<vector<int>> adjacencyLists;
Graph::Graph(int vertices) : adjacencyLists{vertices} {}
由于它还没有在标准中,我会使用一个vector
(它实际上是dynarray
的超集,所以它的用法实际上是相同的):
vector<vector<int>> adjacencyLists;
Graph::Graph(int vertices) : adjacencyLists{vertices} {}
或者,如果您真的想自己管理这一切,您可以将其存储在unique_ptr
中:
unique_ptr<vector<int>[]> adjacencyLists;
int numVertices;
Graph::Graph(int vertices)
: adjacencyLists{new vector<int>[vertices]}
, numVertices{vertices}
{}
使用这种方法,您几乎肯定也希望存储adjacencyLists
的大小(如上所示),否则您将无法遍历数组,因为您不知道它有多大。
无论你做什么,永远不要让原始指针自己的记忆。它应该始终是一个unique_ptr
、shared_ptr
或一些容器。如果使用 delete
关键字,则它不是现代 c++。
更改:
vector<int> adjacencyLists[];
自:
vector<int>* adjacencyLists;
相关文章:
- 如何在向量数组中插入元素?
- 不同大小的向量数组的大小 cpp
- 很好的语法来获取对向量/数组数据的大小引用?
- 指向 c++ 中的向量数组并将其发送到函数的指针
- 初始化向量数组,其中每个向量的大小为 0
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 如何使用结构体的向量数组?
- C++:向量数组
- 在C++中通过引用传递向量数组
- 向量数组"Cannot access memory at address"
- 构造不同类型的C++向量数组
- 向量数组的均值和众数 - 如何对函数进行较小的改进
- C++:初始化(新)一个不同初始大小的向量数组
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 销毁C++中的向量数组
- 继承向量/数组/列表并更改其大小
- 如何输出属于向量数组的结构字符串
- 如何通过引用传递向量数组
- 在向量数组中获得前五个最大的结果
- 为什么"new vector<int>[5]"不创建向量数组?