Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何复制列表向量?_C++_Oop_Data Structures_Vector_Copy - Fatal编程技术网

C++ 如何复制列表向量?

C++ 如何复制列表向量?,c++,oop,data-structures,vector,copy,C++,Oop,Data Structures,Vector,Copy,在我的程序中,我需要将private数据结构复制(甚至使用)到完全不同类的.cpp文件中。目前,我甚至在远程访问它时遇到困难,当我试图打印它时,它会出现故障。下面是我的类的简化版本,数据结构如下: class Graph { private: class Edge { public: Edge(string vertex, int weight) { m_vertex = vertex; m_

在我的程序中,我需要将
private
数据结构复制(甚至使用)到完全不同类的.cpp文件中。目前,我甚至在远程访问它时遇到困难,当我试图打印它时,它会出现故障。下面是我的类的简化版本,数据结构如下:

class Graph
{
private:
    class Edge
    {
    public:
        Edge(string vertex, int weight)
        {
            m_vertex = vertex;
            m_weight = weight;
        }
        ~Edge(){}
        string m_vertex;
        int m_weight;
    };
    vector< list<Edge> > adjList;
public:
    Graph();
    ~Graph();
    vector < list < Edge > > get_adjList(){return adjList;}
    //Other functions....

};
简而言之,我想知道这个堆栈跟踪是什么(我以前有过seg故障,但我从未见过)。我想知道如何从
#包括“Graph.h”
的其他文件中的类图正确访问数据结构。我也不确定如何在
testPrint()中复制我的对象。为什么这在
Graph.cpp
中工作得很好

void Graph::set_array(string vertex)
{
    //increment vector size by 1 and insert a new Edge object into the vector of linked lists
    cout << "ADDING " << vertex << " TO VECTOR" << endl;
    adjList.resize(adjList.size() + 1);
    adjList[adjList.size() - 1].push_back(Edge(vertex, 0));
}
void图::设置数组(字符串顶点)
{
//将向量大小增加1,并将新的边对象插入到链表的向量中
库特
如您所述,
Graph
的默认构造函数不做任何操作。因此,此时,
Graph.adjList
为空

graph.adjList = graph.get_adjList();
这是一个无意义的语句,它从自身的副本分配给
graph.adjList
。因为它以前是空的,所以现在仍然是空的

cout << graph.get_adjList()[0].front().m_vertex << " TEST!" << endl;

Graph的默认构造函数能做什么呢?
Graph
Graph(){}
析构函数也是空的。您应该使用
-g
标志进行编译以获得调试符号,这样您就有了更容易理解的回溯。您还可以通过“const reference”(而不是通过值)传递对象为了避免复制。get_adjList真的应该返回一个全新的副本,而不是一个引用吗?图形结构需要包含什么?列表的向量?@user3040019:恐怕我不理解这个问题,或者至少我没有足够的关于您的问题的信息,不知道如何回答它。对不起,我的意思是什么图“构造函数”需要包含/@user3040019:为了使该
cout
语句有效,它至少需要放置一个元素(一个
list
)进入
调整列表
,可能通过
向后推
,或
向后放置
调整大小
。您还尝试访问列表的第一个元素,因此它还需要放置至少一个元素(一个
边缘
)在您刚才添加的列表中。我将添加检查以确保数据结构中是否没有元素。我正在考虑将我的构造函数设置为这样:
Graph::Graph(){new vector>;}
我的想法是,这将创建一个新的向量,我们可以使用graph.h中声明的引用向量。不过,我不太确定它是否有效。
Graph graph;
graph.adjList = graph.get_adjList();
cout << graph.get_adjList()[0].front().m_vertex << " TEST!" << endl;