【问题标题】:initialising array of vectors in constructor在构造函数中初始化向量数组
【发布时间】:2019-03-04 15:05:32
【问题描述】:

我有一个名为 Graph 的类。有这个顶点类的成员。我已经在构造函数中初始化了顶点。此外,还有一个向量成员数组。我希望向量的数量等于顶点。例如,如果 vertices = 5 那么我的向量数组应该是这样的。 向量 v[5]; 我如何在构造函数中执行此操作,因为我只会知道构造函数中顶点的值?

class Graph
{

private:
    int vertices;
    std::vector<int> adj[];
public:
    Graph(int v); //constructor
    // add an edge
    void addEdge(int u, int v);
    //print bfs traversal of graph
    void bfs(int s); // s is a source from where bfs traversal should 
                     //start

};

Graph :: Graph(int v)
{
   vertices = v;
}

【问题讨论】:

    标签: arrays oop c++11 vector


    【解决方案1】:

    由于您只在运行时知道顶点的值,因此不能使用 C 样式数组或 std::array,因为它们需要在编译时知道大小。

    您可以改用另一个向量:

    std::vector<std::vector<int>> adj;
    

    【讨论】:

    • 我可以在新的内存分配中使用它吗?像这样: adj = new vector (vertices);
    • @GauravSahu 你为什么会这样?外部std::vector 自己处理分配。一般来说,not 更喜欢手动分配 - 这很容易出错,并且您可以在 95-99% 的时间使用标准容器。
    • @lisyarus 我是 STL 的新手。如何在构造函数中初始化向量的向量?
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多