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?
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?
adjLists
has type std::vector<int>*
, so simple solution is simply returning that.
std::vector<int>* Graph::getVector() const
{
return adjLists;
}
Assigning what is returned ((a pointer to) an array of std::vector<int>
) to std::vector<int> myVector
requires some non-trivial conversion.
std::vector<int>* adjLists(1);
(initialize a pointer by integer 1
) is invalid.
std::vector<int>* adjLists;
is OK but not recommended because manipulating raw pointers have high risk of embedding bugs.
std::vector<std::vector<int> > adjLists;
is better.
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.