调用std :: vector :: push_back()是否正在改变向量中的前一个元素?

时间:2013-11-14 11:35:08

标签: c++ vector

首先,一些煮熟的代码:

#ifndef UNDIRECTED_GRAPH_HPP
#define UNDIRECTED_GRAPH_HPP

#include <vector>
#include <iostream>

template <typename T>
struct undirected_graph
{
    struct node
    {
        T data;
    };

    struct edge
    {
        node& node0;
        node& node1;
    };

    ~undirected_graph() {
        for (auto n : nodes_) delete n;
        for (auto e : edges_) delete e;
    }

    const node& add_new_node(const T& data);

private:
    std::vector<node*> nodes_;
    std::vector<edge*> edges_;
};

template <typename T>
const typename undirected_graph<T>::node&
undirected_graph<T>::add_new_node(const T& data)
{
    node *n = new node { data };
    nodes_.push_back(n);
    for (auto x : nodes_) std::cout << x->data.pos.x << "," << x->data.pos.y << std::endl;
    return *n;
}

#endif

问题存在于undirected_graph::add_new_node(const T& data)中。我将输出添加到控制台以进行调试,因为到目前为止我只使用这个类和我自己的数据类型。每当我调用此方法时,nodes_向量中的前一个条目似乎都被更改为最后一个元素。

我认为它可能与我选择存储在我的图表中的数据类型有关,所以我也添加了调用它的代码部分:

// Somewhere in dungeon_generator.cpp ...
undirected_graph<const DungeonLayout::Room&> graph;

for (auto room : dungeon->rooms) {
    graph.add_new_node(room);
}

所以要么我的方法有缺陷,要么我称之为有缺陷,或两者都有。但我似乎无法弄清楚出了什么问题!有人可以帮助我吗?

为了进一步说明问题,我已经为该方法添加了几个调用的输出。 dungeons_->rooms容器包含随机生成位置的一堆房间(由pos属性表示)

2,2
9,9
9,9
3,2
3,2
3,2
2,6
2,6
2,6
2,6
9,3
9,3
9,3
9,3
9,3

1 个答案:

答案 0 :(得分:2)

似乎存储对临时变量room的引用。变化

undirected_graph<const DungeonLayout::Room&> graph;

undirected_graph<DungeonLayout::Room> graph;