[英]Accessing Vector outside of class
我正在处理从这里检索到的 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;
}
我在公众中尝试了以下 function 并导致错误:
const std::vector<int, std::allocator<int> >& Graph::getVector() const
{
return adjLists;
}
有没有办法获得 adjLists?
拥有std::vector<int>* adjLists;
是一种好的编码习惯吗? 并调用adjLists = new std::vector<int>[vertices];
创建矩阵还是将其定义为std::vector<int>* adjLists(1);
然后在 Graph 调用中调整它的大小?
adjLists
的类型为std::vector<int>*
,所以简单的解决方案就是简单地返回它。
std::vector<int>* Graph::getVector() const
{
return adjLists;
}
将返回的内容((指向)一个std::vector<int>
数组)分配给std::vector<int> myVector
需要一些非平凡的转换。
std::vector<int>* adjLists(1);
(通过 integer 1
初始化指针)无效。
std::vector<int>* adjLists;
可以,但不推荐,因为操作原始指针具有嵌入错误的高风险。
std::vector<std::vector<int> > adjLists;
更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.