如何解决在类外访问 Vector
问题 1
我正在处理从 here 检索的这个 BFS 代码,我对代码进行了一些更改,现在我想访问主要部分中类之外的 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;
}
const std::vector<int,std::allocator<int> >& Graph::getVector() const
{
return adjLists;
}
有没有办法获得 adjLists ?
问题 2:
使用 std::vector<int>* adjLists;
和调用 adjLists = new std::vector<int>[vertices];
来创建矩阵是一种很好的编码习惯,还是我应该将其定义为 std::vector<int>* adjLists(1);
然后在 Graph 调用中调整它的大小?
解决方法
问题 1
adjLists
的类型为 std::vector<int>*
,所以简单的解决方案就是返回它。
std::vector<int>* Graph::getVector() const
{
return adjLists;
}
将返回的内容((指向)std::vector<int>
数组)分配给 std::vector<int> myVector
需要一些非平凡的转换。
问题 2
std::vector<int>* adjLists(1);
(用整数 1
初始化指针)无效。
std::vector<int>* adjLists;
可以,但不推荐,因为操作原始指针有很高的嵌入错误的风险。
std::vector<std::vector<int> > adjLists;
更好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。