[英]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.