我有一个 cpp 问题,我不知道出了什么问题..也许你可以帮助我:)。
我正在尝试实现图表的数据结构。在此图中,我将连接一些具有较小欧氏距离的节点,但在第二次迭代时,我的迭代器将指向 0x0。仅当我将这两个节点的距离给出到 std::cout 时,才会出现这种情况。这是我的代码:
for(vector<Node*>::iterator n1 = g->getNodes().begin(); n1 != g->getNodes().end(); ++n1)
{
for(vector<Node*>::iterator n2 = g->getNodes().begin(); n2 != g->getNodes().end(); ++n2)
{
if(*n2 == 0)
{
// This will be entered after the first iteration of n2.
cout << "n2 null" << endl;
continue;
}
double distance = (*n1)->getDistance(*n2); // just euclidean distance
if(distance <= minDistance)
{
// This works fine:
cout << "(" << *n1 << "," << *n2 << ") << endl;
// This brings me a "Segmentation fault"
cout << "(" << *n1 << " , " << *n2 << ") -> " << distance << endl;
}
}
}
这是嵌套循环所拥有的吗?谁能告诉我是我的错吗?多谢!
编辑:这里还有一些代码:node.h
#ifndef NODE_H_
#define NODE_H_
#include <vector>
#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
class Node
{
private:
int x, y, z;
public:
Node(int x, int y, int z) : x(x), y(y), z(z)
{
}
inline int getX() { return x; }
inline int getY() { return y; }
inline int getZ() { return z; }
inline double getDistance(Node* other)
{
return sqrt(pow(x-other->getX(), 2) + pow(y-other->getY(), 2) + pow(z-other->getZ(), 2));
}
};
#endif
graph.h
#ifndef GRAPH_H_
#define GRAPH_H_
#include <vector>
#include "node.h"
using namespace std;
class Graph
{
private:
vector<Node*> nodes;
public:
~Graph()
{
while(!nodes.empty())
{
delete nodes.back(), nodes.pop_back();
}
}
inline vector<Node*> getNodes() { return nodes; }
inline int getCountNodes() { return nodes.size(); }
bool createNode(int x, int y, int z)
{
nodes.push_back(new Node(x, y, z));
return true;
};
#endif
main.cc
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include "model/graph.h"
using namespace std;
int main()
{
Graph *g = new Graph();
int nodeDistance = 100;
for(int z = 0; z <= 300; z += nodeDistance)
{
for(int x = 0; x <= 500; x += nodeDistance)
{
for(int y = 0; y <= 300; y += nodeDistance)
{
g->createNode(x, y, z);
}
}
}
for(vector<Node*>::iterator n1 = g->getNodes().begin(); n1 != g->getNodes().end(); ++n1)
{
for(vector<Node*>::iterator n2 = g->getNodes().begin(); n2 != g->getNodes().end(); ++n2)
{
if(*n2 == 0)
{
// This will be entered after the first iteration of n2.
cout << "n2 null" << endl;
continue;
}
double distance = (*n1)->getDistance(*n2); // just euclidean distance
if(distance <= nodeDistance)
{
// This works fine:
cout << "(" << *n1 << "," << *n2 << ") << endl;
// This brings me a "Segmentation fault"
cout << "(" << *n1 << " , " << *n2 << ") -> " << distance << endl;
}
}
}
delete g;
return 0;
}