c++ - 调用 std::vector::push_back() 会更改 vector 中先前的元素吗?

标签 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_ vector 中的先前条目似乎都被更改为最后一个元素。

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

// 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

最佳答案

似乎您存储了对临时变量room的引用。改变

undirected_graph<const DungeonLayout::Room&> graph;

undirected_graph<DungeonLayout::Room> graph;

关于c++ - 调用 std::vector::push_back() 会更改 vector 中先前的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976604/

相关文章:

c++ - 叉积的输出

c++递归调用不将项目推送到 vector

math - 某个角度的扰动向量

c++ - 使用 Boost.Asio 获取本地 IP 地址

c++ - RapidXML:无法打印 - 编译时错误

c++ - 通过复制将 opengl 对象包装到 C++ 类中

C++ 通过引用传递 Vector 字符指针

c++ - 相当于windows事件的跨平台

c++ - 推导容器和 initializer_list-s 的模板函数

c++ - 无法通过引用传递值 C++