c ++中的向量初始化

时间:2018-05-23 15:10:26

标签: c++ vector initialization

有人可以向我解释为什么Graph构造函数中的verticies.size()等于'4'但是在addEdge中再次调用verticies.size()等于0?该程序在verticies [fromVertex] .addEdge(toVertex)崩溃,因为verticies的大小为0.

我确信这是我应该知道的,但我不会在哪里出错。

class Vertex {

public:
    int value;
    vector<int> adj;
    bool isVisited = false;

    Vertex(int _value)
    {
        value = _value;
    }

    void addEdge(int destination)
    {
        adj.push_back(destination);
    }   
};

class Graph
{

public:

    int vertexCount;    // No. of vertices            
    vector<Vertex> verticies;

    Graph(int _vertexCount)
    {
        this->vertexCount = _vertexCount;
        vector<Vertex> verticies;
        for (size_t i = 0; i < _vertexCount; i++)
        {
            Vertex v = Vertex(i);
            verticies.push_back(v);
        }
        cout << "verticies count " << verticies.size() << endl;
    }
    void addEdge(int fromVertex, int toVertex)  
    {
        cout << "verticies count in addEdge: " << verticies.size() << endl;
        verticies[fromVertex].addEdge(toVertex); 
    }
    void findPath(int fromVertex, int toVertex, vector<int> pathSoFar)  
    {
        pathSoFar.push_back(fromVertex);
        if (fromVertex == toVertex)
        {
            for (int i = 0; i < pathSoFar.size(); i++)
            {
               cout << pathSoFar.at(i) << " ";
            }
            cout << endl;
            return;
        }
        else
        {
            for (size_t i = 0; i < verticies[fromVertex].adj.size(); i++)
            {   
                int nextToVisit = verticies[fromVertex].adj.at(i);
                if (verticies[nextToVisit].isVisited == false)
                {
                    findPath(nextToVisit, toVertex, pathSoFar);
                }

            }
        }
    }
};

int main()
{
    // Create a graph given in the above diagram
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);


    vector<int> path;
    g.findPath(2, 1, path);

    return 0;
}

2 个答案:

答案 0 :(得分:7)

  

有人可以向我解释为什么在Graph构造函数中使用verticies.size()   等于'4',但在addEdge再次调用时,verticies.size()等于0?

这是因为这是两个不同的对象。这里

Graph(int _vertexCount)
{
    this->vertexCount = _vertexCount;
    vector<Vertex> verticies;
    // ....
}

您正在创建一个名为verticies的本地矢量,该矢量会隐藏成员变量。简单地删除该行应该没问题。我的意思是你已经宣布成员,不需要做两次;)。

此外,我建议您在填充数据之前调整向量大小,或者至少保留所需的容量。

答案 1 :(得分:1)

在这里你正在影响你的课堂领域:

Graph(int _vertexCount)
{
    this->vertexCount = _vertexCount;
    vector<Vertex> verticies;  // <--- exactly here
    for (size_t i = 0; i < _vertexCount; i++)
    {
        Vertex v = Vertex(i);
        verticies.push_back(v);
    }
    cout << "verticies count " << verticies.size() << endl;
}

您正在本地(在构造函数的上下文中)执行所有操作verticies而不是Graph::verticies。顺便说一下,正确的英文复数形式是vertices