【发布时间】:2018-03-16 20:47:55
【问题描述】:
我正在为我的班级编写一个 C++ 程序,用于计算一组输入边的 MST(最小生成树)。到目前为止,我已经编写了一些函数,并且在尝试传递一个包含最小生成树的“边”的数组时遇到了困难。如何将此数组从readGraph 函数传递给insertEdge 函数?
当我尝试使用 '&' 时,编译器会显示此错误:
error: cannot convert 'int**' to 'int*' for argument '4' to 'void insertEdge(int, int, int, int*)'|
Instructions for the assignment
#include "iostream"
#include <cstdio>
#include "equiv.h"
#include <string.h>
using namespace std;
// Edge structure which creates 3 integer variables(vert1, vert2, weight)
// and uses a constructor to initialize these variables.
// "vert1" & "vert2" hold 2 vertex numbers and "weight" holds the weight of a edge.
struct Edge
{
int vert1;
int vert2;
int weight;
Edge() : vert1(0), vert2(0), weight(0)
{
}
};
const int maxEdges = 100;
struct Graph
{
int vertGraph;
int edgeGraph;
int edgeArray [maxEdges];
int physicalSizeArray;
Graph(int nv) : vertGraph(0), edgeGraph(0), edgeArray(), physicalSizeArray(0)
{
}
};
// insertEdge(u, v, w, g) inserts an edge of weight w between vertices
// u and v into graph g.
//
// If there is not enough room in g to add the edge, then
// insertEdge does nothing.
void insertEdge(int u,int v,int w,int g[])
{
int arrayPosition = 0;
for (int i = 0; i <= maxEdges; i++)
{
if (g[i] == 0) {
if(arrayPosition == 0)
{
g[i] = u;
arrayPosition++;
}
else if(arrayPosition == 1)
{
g[i] = w;
arrayPosition++;
}
else if(arrayPosition == 2)
{
g[i] = v;
break;
}
}
}
}
void readGraph(int G[])
{
Edge p1;
bool nextEdge = true;
int i = 0;
cout << "Enter number of vertices: ";
cin >> i;
cout << "Enter two vertices separated by a space and followed by a weight for edge: ";
while(nextEdge)
{
cin >> (p1.vert1, p1.vert2, p1.weight);
insertEdge(p1.vert1,p1.vert2,p1.weight,G);
if(p1.vert1 == 0)
{
nextEdge = false;
}
}
}
int main()
{
int arrayTest[20];
readGraph(&arrayTest);
return 0;
}
【问题讨论】:
-
@the_storyteller 我试过了,但编译器显示这个......错误:无法将参数 '4' 的 'int**' 转换为 'int*' 到 'void insertEdge (int, int, int, int*)'|
-
@the_storyteller 你确定吗?如果你这样做,你不只是取消引用指向第一个元素的指针,即获取第一个元素吗?我认为在调用 readgraph 时,OP 应该发送
readGraph(arrayTest)而不是readGraph(&arrayTest) -
你应该问问你的教授你是否可以使用
std::vector。
标签: c++ arrays function greedy kruskals-algorithm