[英]Accessing Vector outside of class
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 代码,我稍微更改了代码,现在我想访问主要部分中 class 之外的 adjLists 向量。
// 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:我在公众中尝试了以下 function 并导致错误:
const std::vector<int, std::allocator<int> >& Graph::getVector() const
{
return adjLists;
}
Is there a way to get adjLists?有没有办法获得 adjLists?
Is it a good coding practice to have std::vector<int>* adjLists;
拥有
std::vector<int>* adjLists;
是一种好的编码习惯吗? and a call adjLists = new std::vector<int>[vertices];
并调用
adjLists = new std::vector<int>[vertices];
to create the matrix or shall I define it as std::vector<int>* adjLists(1);
创建矩阵还是将其定义为
std::vector<int>* adjLists(1);
then resize it in the Graph call?然后在 Graph 调用中调整它的大小?
adjLists
has type std::vector<int>*
, so simple solution is simply returning that. adjLists
的类型为std::vector<int>*
,所以简单的解决方案就是简单地返回它。
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>
数组)分配给std::vector<int> myVector
需要一些非平凡的转换。
std::vector<int>* adjLists(1);
(initialize a pointer by integer 1
) is invalid. (通过 integer
1
初始化指针)无效。
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.更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.