如何创建向量数组

How to create an array of vectors

本文关键字:向量 数组 创建 何创建      更新时间:2023-10-16

如何正确初始化向量数组?

图.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_ptrshared_ptr或一些容器。如果使用 delete 关键字,则它不是现代 c++。

更改:

vector<int> adjacencyLists[];

自:

vector<int>* adjacencyLists;