C++ 遍历结构元素的向量
这是我的密码:C++ 遍历结构元素的向量,c++,vector,C++,Vector,这是我的密码: #include<iostream> #include <vector> #include <stack> using namespace std; struct node { node *parent; int x, y; float f, g, h; }; node findmin(vector<node> open) { int mini=2000000; node iter
#include<iostream>
#include <vector>
#include <stack>
using namespace std;
struct node {
node *parent;
int x, y;
float f, g, h;
};
node findmin(vector<node> open)
{
int mini=2000000;
node iter,mininode;
std::vector<node>::iterator it;
for(it = open.begin(); it != open.end(); ++it) {
if(it.f<mini)
{
mini=it.f;
mininode=it;
}
}
return mininode;
}
int main() {
vector<node> open;
vector<node> closed;
node start;
start.x=50;
start.y=50;
start.f=0;
start.g=0;
start.h=0;// you can take it as zero. works instead of the actual distnace between goal and start.
node goal;
goal.x=53;
goal.y=50;
goal.f=-1;
goal.g=-1;
goal.h=0;
// put the starting node on the open list
open.push_back(start);
node current,temp;
current=findmin(open);
// THE EDIT CODE GOES HERE.
return 0;
}
为什么这不起作用?我看不出有什么原因!open.empty()。所以在主循环中有一个无限循环。我认为这是错误的
findmin
功能
node findmin( vector<node> open ) {
int mini = 2000000;
node iter, mininode;
std::vector<node>::iterator it;
for( it = open.begin( ); it != open.end( ); ++it ) {
if( it->f<mini ) {
mini = it->f;
mininode = *it;
}
}
return mininode;
}
for (vector<node>::iterator it = open.begin(); it != open.end(); /* ++it*/) {
if(*it == current)
it = open.erase(it);
else
++it;
}
for(vector::iterator it=open.begin();it!=open.end();/*++it*/){
如果(*it==当前)
它=打开。擦除(它);
其他的
++它;
}
但您需要重载操作符==
,或者在if
语句中写入一些其他条件
请记住,迭代器的建模类似于指针,因此必须正确地取消对它们的引用,例如
it->f
。或者使用一个。你用的是什么愚蠢的编译器来编译这个?it->f
可以工作,但我还有一个问题。参考上面的编辑。所以这是一个编译错误。另外,请解决上面编辑部分中的另一个查询。应该可以,但不知道为什么会出现以下错误:与“operator==”不匹配(操作数类型为“node”和“node”)
@userxigy我已经提到过(请看答案中的最后一行)。如果您需要重载操作符,您可以这样做,例如bool操作符==(const-node&n1,const-node&n2){return n1.x==n2.x&&n1.y==n2.y;}
I编写:If((it->x==current.x)&(it->y==current.y))
node findmin( const vector<node>& open ) { /**/ }
for (vector<node>::iterator it = open.begin(); it != open.end(); /* ++it*/) {
if(*it == current)
it = open.erase(it);
else
++it;
}