我正在为我的类编写一个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;
}
答案 0 :(得分:0)
有三种方法可以将数组作为参数传递给函数:
readGraph(arrayTest);
所有这三个可能的声明产生类似的结果,因为它们都告诉编译器将接收整数指针作为函数的参数。
如何将此数组从readGraph函数传递给insertEdge 功能
std::array
您不应该传递数组的内存地址,而应该传递数组本身,即通过指定不带索引的数组名称来指向数组的指针。
还要注意C ++不对正式参数执行边界检查,因此最好选择std::vector
或c-array
而不是T T
Te Te
Tes Tes
Test Test
Test Tes
Tes Te
Te T
T
。