首先,我知道这里有很多类似的帖子,但我一直在浏览它们一段时间,我无法解读我需要做的事情。所以关于我的问题:我正在将我以前在C中编写的Graph类转换为C ++。由于我如何初始化它,我无法将数组转换为向量。如果有人能指出我正确的方向,那就太棒了。您可以看到我开始尝试将数组char *颜色转换为矢量颜色,但它不起作用并且G ++错误消息很长一段时间。我遗漏了#include语句,但我保证这些不是问题。
Graph.h
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 * distance数组应该是int的向量,List ** edgeDist和whatnot应该是List *的向量。它只是在我需要帮助的Graph.cpp函数Graph :: prepGraph(int n)中初始化它。语法有点诅咒,但我试图在不完全破坏它的情况下展示我想要做的事情。换句话说,我一直抱怨的那些static_cast(calloc(无论如何))语句?帮我摆脱那些。
答案 0 :(得分:0)
您的代码中存在许多问题。我会试着给你一个开始:
//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
}