【发布时间】: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));
}
}
我遵循了一个教程。教程中的那个人有相同的代码,但没有出错。我不确定如何解决这个情报问题。
【问题讨论】:
-
for each (auto var in vertex_list)不是标准的 C++ 语法。改用基于标准范围的 for 循环:en.cppreference.com/w/cpp/language/range-for 或使用标准算法。 -
这是跟随随机教程的问题。他们很少告诉你他们何时使用扩展 docs.microsoft.com/en-us/cpp/dotnet/for-each-in?view=vs-2019 - 取而代之的是一本关于 C++ 的好书,然后通过 stackoverflow.com/questions/388242/…
-
C++ 没有
for each。 -
真的 c++ 都没有吗?
标签: c++ algorithm data-structures graph