2015-01-27 4 views
0

Моя программа вылетает при попытке запуска функции initialize_graph. Я пропустил все остальные функции. Это один из моих первых случаев работы с векторами. Заголовок graph.h будет ниже основного. Мне просто нужен кто-то, кто поможет мне инициализировать вектор с объектом графа, у которого указатель на голове равен нулю. Я смогу взять его оттуда. Спасибо, что посмотрели.Как инициализировать вектор указателей?

#include <cstdlib> 
#include <iostream> 
#include <vector> 
#include "graph.h" 

using namespace std; 

vector<graph*> adj_list; // one dimensional vector; each position in the vector stores a pointer to the head of a linked list 


void graph::initialize_graph(int num_of_vertices, int num_of_edges) 
{ 
    cout << "Doing push back"; // want to push back the same obj. call it graph* graph_obj (where head is null) 
    //adj_list.resize(num_of_vertices); 
    graph *graph_obj; 
    graph_obj -> head = NULL; 
    for(int k = 0; k < num_of_vertices; k++) 
    { 
     adj_list.push_back(graph_obj); 
    } 
    cout << "Pushback complete"; 
} 

int main() 
{ 
    int num_of_vertices, num_of_edges, vertex1, vertex2, function; 
    graph graph_obj; 


    while(1) 
    { 

    cout<<"1 - initialize graph" <<endl; 
    cout<<"2 - insert an edge to the graph" <<endl; 
    cout<<"3 - delete an edge from the graph" <<endl; 
    cout<<"4 - list all edges in the graph" <<endl; 
    cout<<"5 - list all of the neighbors for a particular vertex" << endl; 
    cout<<"6 - list all of the vertices with no incoming edges" << endl << endl; 

    cout<<"Choose a function (1 - 6): "; 
    cin>>function; 
    cout<<endl<<endl; 

    switch(function) 
    { 
     case 1: 
      cout<<"Enter the number of vertices in the graph: "; 
      cin>>num_of_vertices; 
      cout<<endl<<"Enter the number of edges in the graph: "; 
      cin>>num_of_edges; 
      cout<<endl<<endl; 
      cin.get(); 
      graph_obj.initialize_graph(num_of_vertices, num_of_edges); 
      break; 

    case 2: 
      cout<<"To enter an edge X -> Y (an edge from node X to node Y), use the following format: X Y (the names of the two vertices separated by a single space)" << endl; 
      cout<<"Enter the edge to insert into the graph: "; 
      cin>>vertex1>>vertex2; 
      cout<<endl<<endl; 
      graph_obj.insert_edge(vertex1, vertex2);   
      break; 

    case 3: 
      cout<<"To enter an edge X -> Y (an edge from node X to node Y), use the following format: X Y (the names of the two vertices separated by a single space)" << endl; 
      cout<<"Enter the edge to delete from the graph: "; 
      cin>>vertex1>>vertex2; 
      cout<<endl<<endl; 
      graph_obj.delete_edge(vertex1, vertex2);   
      break; 

    case 4: 
      graph_obj.list_all_edges(num_of_vertices); 
      break; 

    case 5: 
      cout<<"Enter the vertex to list all of the neighbors for: "; 
      cin>>vertex1; 
      cout<<endl<<endl; 
      graph_obj.list_all_neighbors(vertex1, num_of_vertices); 
      break; 

    case 6: 
      graph_obj.no_incoming_edges(num_of_vertices); 


    } //end switch 



    } //end while 

    system("PAUSE"); 
    return 0; 
} 

class graph //class for the graph data structure 
{ 
    public: 
    void initialize_graph(int num_of_vertices, int num_of_edges); //creates a new directed graph 
    void insert_edge(int vertex1, int vertex2); // inserts a directed edge (V1 - > V2) into the graph 
    void delete_edge(int vertex1, int vertex2); // deletes an edge (V1 -> V2) from the graph 
    void list_all_edges(int num_of_vertices); // lists all of the edges in the graph 
    void list_all_neighbors(int vertex1, int num_of_vertices); // lists all of the neighbors for a particular vertex 
    void no_incoming_edges(int num_of_vertices); // lists all of the vertices with no incoming edges 

    private: 
    graph *prev; //pointer to the previous node in the linked list (used in the adjacency list implementation only) 
    graph *next; //pointer to the next node in the linked list (used in the adjacency list implementation only) 
    graph *head; //pointer to the head of a linked list   (used in the adjacency list implementation only) 
    int edge; // the id of the vertex that there is an edge to (used in both implementations) 

}; 
+3

Аварии? Я не думаю, что 'push_back (* graph_obj)' должен даже компилироваться. – zmbq

+0

Моя ошибка. Я проверял некоторые вещи и забыл изменить это, что было. –

+0

Ваша петля, даже если вы использовали ответы ниже, толкает то же значение указателя на вектор. Это ваше намерение? Вектор, заполненный тем же значением? – PaulMcKenzie

ответ

0

Немного проблемы здесь:

graph *graph_obj; 
graph_obj -> head = NULL; 

Вы создаете неинициализированный указатель, а затем сразу dereferincing его. Вам нужно будет создать объект для указателя, на который нужно указать.

+0

Я думаю, что мне нужно использовать «новый» звонок где-нибудь? –

+1

@Eidbanger: Кажется, вероятно. –

3

Вы никогда не выделяется новая память из кучи для указателя на:

graph *graph_obj; 

Это значение указателя иначе не определено, поэтому это сбой.

Инициализировать его:

graph *graph_obj = new graph(); // Depending on your constructor. 

Edit: Кроме того, если вы собираетесь повторно использовать этот указатель и толкая его обратно на контейнер, вам необходимо создать новый указатель на элемент в контейнер (не забудьте удалить его позже!).

+0

Хорошо спасибо! Но можно ли сказать, что graph_obj -> head = NULL; после инициализации graph_obj? –

+0

До тех пор, пока последующие узлы графа знают, имеет ли голова нулевое значение, я не понимаю, почему это проблема. Вы можете определить его как nullptr вместо NULL, если вы используете C++ 11. – PDizzle745

Смежные вопросы