我可以在 cpp 中使用带有向量的嵌套循环吗?

2024-03-19

我有一个 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;
}

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

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

一般来说,返回向量的副本没有什么问题。但是,当您这样做时,如果您确实想要一个函数,则必须确保调用这样的函数copy,而不是同一个向量。使用getNodes就您想要完成的任务而言,您使用的功能不是有效的用法。

错误在这里:

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

The fix:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以在 cpp 中使用带有向量的嵌套循环吗? 的相关文章

随机推荐

  • Android 通过电报发送消息?

    我已经安装了 telegram 应用程序 只想通过 telegram 从我的应用程序向联系人发送消息 字符串 我所发现的只是这个问题 如何通过电报发送 Intent https stackoverflow com questions 216
  • 使用 SaxParser 解析 XML 文档时出现问题 - 2047 个字符限制?

    我创建了一个扩展 SaxParser DefaultHandler 类的类 我的目的是将 XML 输入存储在一系列对象中 同时保留原始 XML 数据的数据完整性 在测试过程中 我注意到一些节点数据在输入时被任意截断 例如 Input
  • 使用 OpenCV 将光栅图像转换为矢量图形?

    我正在寻找使用 OpenCV 将光栅图像转换为矢量数据的可能性 在那里我发现了一个函数cv findContours 这似乎有点原始 更可能是我没有完全理解它 它似乎仅使用黑白图像 没有灰度和彩色图像 并且似乎不接受任何可能有助于噪声图像的
  • 简单存储过程问题

    我正在 VS 2010 SQL Server 2008 中创建一个简单的存储过程 如下所示 CREATE PROCEDURE ReturnPrice carID int price decimal 18 2 output AS SELECT
  • Haskell 平面图

    我是一个对 Haskell 感兴趣的初学者 我一直在尝试自己实现 flatmap gt gt 以更好地理解它 目前我有 flatmap t gt a gt t gt a flatmap flatmap f x xs f x flatmap
  • 如何强制右对齐 UITextView 中的尾随空格?

    我有一个 UITextView 可以左对齐 右对齐或居中 我注意到 如果我右对齐 textView 则 textView 中任何文本行中的任何尾随空格都会被忽略 左对齐时 前导空格不会发生这种情况 从视觉上看 这就是发生的情况 用 来可视化
  • 规范化数组方法和返回值

    是否有任何 JavaScript 数组库可以规范化数组返回值和突变 我认为 JavaScript Array API 非常不一致 有些方法会改变数组 var A 0 1 2 A splice 0 1 reduces A and return
  • 如何检查 Objective-C 中的类?

    Update我修复了代码 以消除重写方法的重复 并通过实现来跟踪属性或方法的发起者Mark https stackoverflow com questions 1890480 how do i inspect a class in obje
  • 定制 Linux GUI:从哪里开始? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我长期以来一直对开发适合我的需求和兴趣的操作系统用户界面感兴趣 当我年轻的时候 我疯狂地使用 Windows 的 Stardock 换
  • 我们什么时候应该实现 Serialized 接口?

    public class Contact implements Serializable private String name private String email public String getName return name
  • 从网页中删除所有 HTML 标签

    我正在做一些 BASH shell 脚本curl 如果我的curl 命令返回任何文本 我就知道有错误 此文本返回者curl通常是 HTML 格式 我想如果我可以去掉所有 HTML 标签 我就可以将生成的文本显示为错误消息 我在想这样的事情
  • NPM 卸载包不起作用

    有人可以帮助我确定卸载 npm 软件包时我的 cli 代码有什么问题吗 当我运行此 cli 代码 如下图所示 时 npm 不会卸载软件包 而是将其添加到我的 node modules 中 我希望这个社区中的某个人可以解决我的问题 并为我带来
  • libgmp-10.dll 丢失

    我最近在我的 64 位 Windows 7 计算机上安装了 MinGW 当我尝试编译最基本的 C 程序时 例如 include
  • 使用 MSBuild 时不会构建私有访问器

    我的构建服务器使用 MSBuild 来构建我的应用程序 我们的单元测试需要访问一些私有成员进行测试 因此我们使用内置的私有访问器 Visual Studio 没有问题 但是当我们将代码推送到构建服务器时 我们收到错误 MyTest cs 9
  • 从数组中删除非唯一行

    我有一个数组a如下 a 1 2 3 4 1 2 我想删除在中多次出现的所有行a并得到c c 3 4 请注意 这与保留唯一行不同 因为我根本不希望出现重复行 我怎样才能做到这一点 第三个输出为unique https www mathwork
  • 重新编译CHM文件

    我正在编写一个脚本 该脚本应该能够向 chm file 反编译后使用hh exe decompile outputFolder fileName chm命令 我得到 html 文件和其他 2 个文件 hhc and hhk扩大 编辑 htm
  • Android -fragmentTransaction.replace() 不适用于支持库 25.1.0

    我使用片段替换 FrameLayoutfragmentTransaction replace Layout
  • SQL Server 表与索引的同义词

    我在 SQL Server 2005 的单个实例上有多个数据库 我在一个数据库上创建了一个同义词来访问另一个数据库上的表 并且在编写查询时 我想使用特定的索引 但是 在评估执行计划 它似乎没有使用它 如果我编写查询来显式访问数据库 它可以工
  • Flask-login:如果login_manager的session_protection设置为“strong”,请记住我不工作

    我正在使用 Flask login 将会话管理集成到我的 Flask 应用程序中 但是如果我设置了 记住我 功能就不起作用会话保护 to strong 但是 如果设置为 它绝对可以正常工作basic 用户加载器 login manager
  • 我可以在 cpp 中使用带有向量的嵌套循环吗?

    我有一个 cpp 问题 我不知道出了什么问题 也许你可以帮助我 我正在尝试实现图表的数据结构 在此图中 我将连接一些具有较小欧氏距离的节点 但在第二次迭代时 我的迭代器将指向 0x0 仅当我将这两个节点的距离给出到 std cout 时 才