mardi 23 mars 2021

Accessing Vector outside of class

Question 1

I am working on this BFS code retrieved from here and I changed the code a little bit and now I want to access the adjLists vector outside of the class in the main section.

// BFS algorithm in C++

#include <iostream>
#include <list>

using namespace std;

class Graph {
  int numVertices;
  std::vector<int>* adjLists;


   public:
  Graph(int vertices);
  void addEdge(int src, int dest);
};

// Create a graph with given vertices,
// and maintain an adjacency list
Graph::Graph(int vertices) {
  numVertices = vertices;
  adjLists = new std::vector<int>[vertices];
}

// Add edges to the graph
void Graph::addEdge(int src, int dest) {
  adjLists[src].push_back(dest);
  adjLists[dest].push_back(src);
}


int main() {
  Graph g(4);
  g.addEdge(0, 1);
  g.addEdge(0, 2);
  g.addEdge(1, 2);
  g.addEdge(2, 0);
  g.addEdge(2, 3);
  g.addEdge(3, 3);


// I want to have a call here for accessing the adjLists vector e.g. std::vector<int> myVector = g.adjLists;

  return 0;
}

I have tried the following function inside the public and it resulted errors:

const std::vector<int, std::allocator<int> >& Graph::getVector() const
{
    return adjLists;
}

Is there a way to get adjLists ?

Question 2:

Is it a good coding practice to have std::vector<int>* adjLists; and a call adjLists = new std::vector<int>[vertices]; to create the matrix or shall I define it as std::vector<int>* adjLists(1); then resize it in the Graph call ?

Aucun commentaire:

Enregistrer un commentaire