[英]Declaring a vector in a .h file, initialize in a .cpp file
首先,我知道这里有很多类似的帖子,但是我一直在仔细阅读它们,因此我很难准确地理解我需要做什么。 接下来是我的问题:我正在将以前用C编写的Graph类转换为C ++。 由于初始化方式,我在将数组转换为向量时遇到了麻烦。 如果有人能指出我正确的方向,那就太好了。 您可以看到我开始尝试将数组char * color转换为vector color,但是它不起作用,并且G ++错误消息长期以来一直是一个晦涩的问题。 我省略了#include语句,但是我保证这些不是问题。
图
using namespace std;
const int INF = INT_MAX;
const int NIL = 0;
class Graph
{
public:
Graph(int n);
Graph(ifstream& in);
~Graph(void);
int getOrder();
int getSize();
int getSource();
int getParent(int u);
int getDist(int u);
void getAdjacencyList(List* L, int u);
void makeNull();
void addEdge(int u, int v, int weight, int color);
void addArc(int u, int v, int weight, int color);
void BFS(int s, int c);
void Prim(int s, int color);
void printGraph();
void printSpanningTree();
private:
bool colorApprover(int, bool ,bool , bool);
void prepGraph(int n);
int order;
int size;
int source;
vector<char> color (16);
int* distance;
int* parent;
List** edgeDist;
List** edgeColor;
List** adj;
};
Graph.cpp
//helper function to streamline the constructors
void Graph::prepGraph(int n){
order = n;
size = 0;
source = NIL;
//color (n + 1);//static_cast<char*>(calloc(n + 1, sizeof(char)));
distance = static_cast<int*>(calloc(n + 1, sizeof(int)));
parent = static_cast<int*>(calloc(n + 1, sizeof(int)));
adj = static_cast<List**>(calloc(n + 1, sizeof(List*)));
edgeDist = static_cast<List**>(calloc(n + 1, sizeof(List*)));
edgeColor = static_cast<List**>(calloc(n + 1, sizeof(List*)));
//discover = static_cast<int*>(calloc(n + 1, sizeof(int)));
//finish = static_cast<int*>(calloc(n + 1, sizeof(int)));
int i;
for(i = 0; i <= n; i++){
color[i] = 'w';
distance[i] = INF;
parent[i] = NIL;
adj[i] = new List();
edgeDist[i] = new List();
edgeColor[i] = new List();
}
}
Graph::Graph(int n){
prepGraph(n);
}
Graph::Graph(ifstream& in){
int n;
in >> n;
prepGraph(n);
while(!in.eof()){
int i, j, weight, color;
in >> i;
in >> j;
in >> weight;
in >> color;
//increment values by 1 so they fit
//into existing graph structure
i += 1;
j += 1;
addEdge(i, j, weight, color);
//cout << "added arc " << i << " " << j << endl;
}
}
我不能只做vector.push_back(),因为其余的代码取决于数组的随机访问属性,因此它们必须准备好进入这里。 我对C ++太陌生,仍然在语法上苦苦挣扎。
编辑:我想我应该提到这使用图形的边列表形式。 List是我也写的一个类,它处理节点。 我只有所有需要转换为C ++向量的C数组,而语法却使我丧命。 例如,int *距离数组应该是ints的向量,而List ** edgeDist和whatnot应该是List *的向量。 它只是在需要帮助的Graph.cpp函数Graph :: prepGraph(int n)中对其进行了初始化。 语法有些刺耳,但我试图显示自己想要做的事情而不完全破坏它。 换句话说,那些我不断抱怨的static_cast(calloc(whatever))语句? 帮我摆脱那些。
您的代码中有很多问题。 我会尝试给你一个开始:
//helper function to streamline the constructors
typedef List<int> NodeList;
struct Node {
char color;
int distance;
int parent;
NodeList adj;
NodeList edgeDist;
NodeList edgeColor;
Node() {
color = 'w';
distance = INF;
parent = 0;
}
}
class Graph
{
...
private:
vector<Node> nodes;
...
}
void Graph::prepGraph(int n){
order = n;
size = 0;
source = NIL;
// nodes will be initialized implicitly
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.