【问题标题】:error: no viable conversion from 'edge' to 'const value_type'?错误:没有从“edge”到“const value_type”的可行转换?
【发布时间】:2016-05-14 21:55:19
【问题描述】:

我只是尝试使用 C++ 中的向量、列表和类来实现有向加权图,但是我收到了这个错误。它给我这个错误的行是第 42:21 行,其中graph[u].push_back(edge(v, w));

#include <iostream>
#include <vector>
#include <list>
#include <stack>

using namespace std;

class edge
{
    private:
        int cost;
        int vertex;
    public:
        edge(int vertex, int cost)
        {
            this->vertex = vertex;
            this->cost = cost;
        }
        int getVertex() const
        {
            return vertex;
        }
        int getCost() const
        {
            return cost;
        }
};

class Graph
{
    private:
        int V;  
        std::vector<std::list<edge> > *graph;
    public:
        Graph(int V);
        void addEdge(int u, int v, int w);
        void DFS();
};
Graph::Graph(int V)
{
    this->V = V;
    graph = new std::vector<std::list<edge> >(V);
}

void Graph::addEdge(int u, int v, int w)
{
    graph[u].push_back(edge(v, w));
}
int main()
{
    return 0;
}

感谢您的帮助!

【问题讨论】:

    标签: c++ list oop vector graph


    【解决方案1】:

    graph 是指向向量的指针,而不是向量,所以你想要:

    (*graph)[u].push_back(edge(v, w));
    

    但它似乎不需要是指针。只是一个普通的向量不是更简单吗?它也可以解决您的内存泄漏问题。

    【讨论】:

    • 如果我将它从指针中删除,它会给我这个错误:错误:没有可行的重载'='图=新的std::vector<:list>>(V) ;
    • 删除new。或者,更好的是,在构造函数中使用成员初始化器。
    猜你喜欢
    • 2018-06-25
    • 2018-03-21
    • 2017-05-29
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2015-08-28
    相关资源
    最近更新 更多