【问题标题】:a 'for each' statement cannot operate on an expression of type "std::vector<Vertex *, std::allocator<Vertex *>>"'for each' 语句不能对“std::vector<Vertex *, std::allocator<Vertex *>>”类型的表达式进行操作
【发布时间】:2020-11-12 02:13:42
【问题描述】:

我正在尝试使用邻接表表示在 C++ 中进行图形实现。我对 C++ 中的“向量”并不陌生。我收到此错误

class Vertex
{
    private:

    public:
    int node_id;
    string value;
    vector< std::pair<Vertex* , int> > adj_list;

    Vertex(int node_id, string value = "" )
    {
        this->node_id=node_id;
        this->value=value;
    }
};

接下来,我正在下一个类中制作一个“顶点”向量。在每个循环中,都会发生此错误。 “IntelliSense:'for each' 语句不能对“std::vector>”类型的表达式进行操作

class graph
{
    private:

public:

    std::vector< Vertex* > vertex_list;

    void add_node(int node_id, string value)
    {
        for each (auto var in vertex_list)      //error here in the initialization of for each
        {
            if (var->node_id==node_id)
            {
                 throw runtime_error("This node id exist already! put another id");
            }
        }
        vertex_list.push_back(new Vertex(node_id, value));
    }
}

我遵循了一个教程。教程中的那个人有相同的代码,但没有出错。我不确定如何解决这个情报问题。

【问题讨论】:

标签: c++ algorithm data-structures graph


【解决方案1】:

你可以使用类似 ranged-for loop 的东西(未经测试的代码)

    for  (auto& var : vertex_list) {
        if (var->node_id==node_id) {
             throw runtime_error("This node id exist already! put another id");
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多