简体   繁体   中英

fill into the a vector holding pointers to lists

I initialize a vector of pointers each pointing to a list of neighbors to implement adjacency-list representation of Graph.

class Graph
{
public:
     Graph(int V) : vertices(V) {}
     // Member functions for Graph class
     void addEdge();
     void print();
     void type(string);
private:
     vector<list<int> *> vertices;
};

addEdge function asks the user to enter the edge from what vertex to another. I think there's a mistake somewhere in filling the vector.

void Graph::addEdge()
{
    int v, w;
    cout << "\nvertex: ";
    cin >> v;
    cout << "\nadjacent: ";
    cin >> w;
    vertices[v]->push_back(w);
}

I need help in this if this is the right way of filling the data structure I introduced or not! if not, what would be the right way of performing the task?

I recommend to use a std::vector<std::vector> for the adjacency matrix of your graph and I advice you not to mix UI with your class (see code below):

class Graph
{
public:
  Graph(std::size_t const n_vert) : adjmat(n_vert, std::vector<int>(n_vert)) {}
     // Member functions for Graph class
     void addEdge(std::size_t const from, std::size_t const to, int const weight);
     void print();
     void type(std::string);
private:
     std::vector<std::vector<int>> adjmat;
};

void Graph::addEdge(std::size_t const from, std::size_t const to, int const weight = 1)
{
  // or `adjmat.at(from).at(to)` for range checking
  adjmat[from][to] = weight;
}

int main ()
{
    Graph G(10);
    int v, w;
    std::cout << "\nvertex: ";
    std::cin  >> v;
    std::cout << "\nadjacent: ";
    std::cin  >> w;
    G.addEdge(v, w);

    return 0;
}

This solution is recommended though, for small Graphs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM