2D对象阵列内存问题C++



当我的输入看起来像这样时:

11

Harry Kate Fred Carol

我的邻接矩阵应该将Harry置于[7][7],Kate置于[7][10],Fred置于[7][5],Carol置于[7][2]。然而,Carol&凯特也被插入到形容词矩阵中的其他位置。我猜这与堆栈和堆内存有关,但我不确定如何找到错误。使用cout语句,似乎没有任何问题。

下方的代码

#include <iostream>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <sstream>
using namespace std;
class Element {
public:
    string name;
    int weight;
    string color;
    //default constructor
    Element(void) {
        name = "";
        weight = 0;
        color = "white";
    }
    //parameterized constructor
    Element(string first) {
        name = first;
        weight = 0;
        color = "white";
    }
    void setBlack() {
        color = "black";
    }
};
class AdjMatrix {
public:
    int size;
    Element ***adj_matrix;
    AdjMatrix(void) {
        size = 0;
        adj_matrix = NULL;
    }
    AdjMatrix(int n) {
        size = n; //sets the size to n
        adj_matrix = new Element **[size];
        for (int i = 0; i < size; i++) {
            adj_matrix[i] = new Element *[i];
        }
    }
    //Destructor class
    ~AdjMatrix(void) {
        delete adj_matrix;
        adj_matrix = NULL;
    }
    //initialize the array with empty elements
    void initialize_matrix() {
        Element *add_element = new Element("");
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++)
                adj_matrix[i][j] = add_element;
        }
    }
};

int convertToASCII(string letter)
{
   int x = letter.at(0);
   int index = x - 65;
    return index;
};
int main(int argc, char *argv[]) {
    string table_size;
    cout<<"";
    getline(cin,table_size);
    int size = atoi(table_size.c_str());
    AdjMatrix *myGraph = new AdjMatrix(size);
    myGraph->initialize_matrix();
string line;
getline(cin, line);
while (getline(cin,line))
{
    if (line.empty())
        break;
    else {
        int x = convertToASCII(line);
        stringstream linestream(line);
        string temp;
        while (linestream >> temp) {
            int z = convertToASCII(temp);
            myGraph->adj_matrix[x][z] = new Element(temp);
        }
    }
}
//Print graph
for (int i = 0; i < myGraph->size; i++) {
    for (int j = 0; j < myGraph->size; j++)
        cout<<"["<<i<<"]["<<j<<"]: "<<myGraph->adj_matrix[i][j]->name<<endl;
}
  return 0;
}

您的程序存在以下问题,应予以纠正。

 //default constructor
    Element(void) 

构造函数应定义为

 //default constructor
    Element()
  • 您应该开始使用std::vector作为2D数组。这将消除手动内存管理。我们应该避免在现代c++中使用原始指针。请参阅下面的SO文章,其中描述了如何使用矢量进行2D阵列

cpp 中使用矢量的二维数组

AdjMatrix(int) ctor中,您错误地构造了三角矩阵(如果这就是您想要的)。试试这个:

AdjMatrix(int n) {
    size = n; //sets the size to n
    adj_matrix = new Element **[size];
    for (int i = 0; i < size; i++) {
        adj_matrix[i] = new Element *[i + 1]; // Or size for a square matrix
    }
}

相关内容

  • 没有找到相关文章

最新更新