我可以在cpp中使用向量嵌套循环吗? [英] Can i use nested loops with vectors in cpp?

查看:137
本文介绍了我可以在cpp中使用向量嵌套循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个cpp问题,我不知道什么错误..也许你可以帮助我:)。
我试图实现图形的数据结构。在这个图中,我将连接一些节点,它们具有小的欧几里德距离,但在第二次迭代时,我的迭代器将指向0x0。这种情况只出现,如果我给这两个节点的距离std :: cout。这是我的代码:

i have a cpp problem and i don't know whats wrong.. maybe you can help me :). I'm trying to implement a data structure for a graph. In this graph i will connect some nodes, which have a small euclidean distance, but at the second iteration, my iterator will point to 0x0. This case appears only, if i give the distance of those two nodes to std::cout. Here is my code:

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;
        }
    }
}


b $ b

这是嵌套循环吗?任何机构都可以告诉我我的错误?非常感谢。

Is this owed by the nested loops? Can any body tell me my fault? Thanks a lot!

编辑:这里是一些更多的代码:
node.h

Here is some more code: 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

strong> graph.h

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 b
$ b

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;
}


推荐答案

一个主要问题是您的 getNodes 函数返回一个向量的副本,而不是原始的向量,因此你在循环中使用的迭代器不会在同一个向量上迭代。

One major issue is that your getNodes function returns a copy of a vector, not the original vector. Therefore your iterators you use in the loops are not iterating over the same vector.

相反,您在嵌套循环中使用的迭代器会遍历4个不同的(但等效的)向量,而不是来自对象的实际向量。

Instead, the iterators you're using in the nested loops are iterating over 4 different (but equivalent) vectors instead of the actual vector from the object in question.

返回一个向量的副本没有什么错误,但是当你这样做,你必须确保你调用这样的函数,如果你真的想要一个复制,而不是相同的向量。使用你所使用的 getNodes 函数,它不是你想要完成什么的有效用法。

There is nothing wrong in returning a copy of a vector in general. However when you do this, you have to make sure you call such a function if you really want a copy, and not the same vector. Using the getNodes function as you used it is not a valid usage in terms of what you are trying to accomplish.

错误在这里:

inline vector<Node*> getNodes()  { return nodes; }

修正:

inline vector<Node*>& getNodes() { return nodes; }

后者确保返回对所讨论的实际向量的引用,而不是实际矢量。您可以添加一个附加函数,如果您仍希望该函数可用,则返回向量作为副本。

The latter ensures that a reference to the actual vector in question is returned, not a copy of the actual vector. You can add an additional function that returns the vector as a copy if you want to still have the functionality available.

这篇关于我可以在cpp中使用向量嵌套循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆