在大学的 C++ 类(class)中,我必须实现一个有向加权图。作为内部表示,我必须实现一个二维数组,它存储有关图中顶点之间边的信息。
好的,我已经实现了一个带有重载 [] 运算符的 C++ 类“TwoDimArray”。
只要我在 main() 中实例化 TwoDimArray 的对象,它就可以很好地工作。但它不是类成员。
我的图形表示类是“DirectedGraph”,并且有一个类型为 TwoDimArray* 的私有(private)成员“adjacencyMatrix”。
在我的 DirectedGraph 类的构造函数中,我最初打算用零填充数组,表示“节点 i 和 j 之间没有边”。
好的,这就是问题所在。我可以写到坐标 [0][2](当用 3 个节点初始化图形时,所以数组应该有 3x3 个单元格)。当尝试在地址 [1][0] 处写入时,赋值操作因段错误而崩溃。因此赋值操作成功 n 次并从 n+1 开始失败(其中 n 是顶点数)。
知道我做错了什么吗?
我的 TwoDimArray 类(第一个标题,然后是实现):
#ifndef TWODIMARRAY_H_INCLUDED
#define TWODIMARRAY_H_INCLUDED
class TwoDimArray{
private:
int* pArr;
int rows;
int cols;
public:
TwoDimArray(int rows, int cols);
int* operator[](int row);
~TwoDimArray();
};
#endif // TWODIMARRAY_H_INCLUDED
实现:
#include <TwoDimArray.h>
TwoDimArray::TwoDimArray(int nrOfRows, int nrOfCols){
rows = nrOfRows;
cols = nrOfCols;
//allocate memory
pArr = new int[rows * cols];
}
int* TwoDimArray::operator [](int row){
return &pArr[row * cols];
}
TwoDimArray::~TwoDimArray(){
delete[] pArr;
}
有向图标题:
#define DIRECTEDGRAPH_H_INCLUDED
#include <string>
#include <list>
#include <Vertex.h>
#include <TwoDimArray.h>
using namespace std;
/**
* DOCUMENTATION
* ======================
* object oriented Implementation
* of the abstract
* Datatype Directed Graph
* as C++ class
*/
class DirectedGraph{
private:
int maxVertices;
list<Vertex> vertices;
TwoDimArray* adjacencyMatrix;
bool edgeExists(string srcName, string tgtName);
int vertexExists(string vName);
public:
//DirectedGraph();
DirectedGraph(int maxVertices);
~DirectedGraph();
void AddVertex(Vertex& v);
void AddEdge(Vertex& source, Vertex& target, int weight);
int getMaxVertices() const;
list<Vertex> getVertexNames()const;
void PrintGraph();
};
#endif // DIRECTEDGRAPH_H_INCLUDED
有向图实现(仅构造函数):
DirectedGraph::DirectedGraph(int maxV){
this->maxVertices = maxV;
//initialize the array
this->adjacencyMatrix = new TwoDimArray(maxV, maxV);
int i = 0;
int j = 0;
for(i = 0; i <= maxVertices - 1; i++){
for(j = 0; j <= maxVertices - 1; j++){
// ==> the fatal assignment
//fails at i = 1 and j = 0
*adjacencyMatrix[i][j]=0;
cout << "assigned " << i << " " << j << "with 0"<<endl;
}
}
}
有什么建议吗? 我想将类成员声明为 TwoDimArray* 而不是 TwoDimArray 是不行的,否则它不会编译。
我也试过的是:
DirectedGraph::DirectedGraph(int maxV){
this->maxVertices = maxV;
//try to instantiate TwoDimArray
TwoDimArray myArr(maxV, maxV);
this->adjacencyMatrix = myArr;
int i = 0;
int j = 0;
for(i = 0; i <= maxVertices - 1; i++){
for(j = 0; j <= maxVertices - 1; j++){
// ==> the fatal assignment
//fails at i = 1 and j = 0
myArr[i][j]=0;
cout << "assigned " << i << " " << j << "with 0"<<endl;
}
}
}
但它在同一点失败了。 我必须承认,我对 C++ 中的指针逻辑不是很熟悉...
有什么建议吗?
提前致谢 罗兰
最佳答案
您违反了Rule of Three .解决这个问题的最简单方法是避免直接分配内存:
class TwoDimArray{
private:
std::vector<int> arr;
int rows;
int cols;
public:
TwoDimArray(int rows, int cols) : arr(rows * cols);
int* operator[](int row) { return &arr[cols*row]; }
};
关于C++:二维数组作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14202593/