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

时间:2014-04-17 02:52:25

标签: c++ memory multidimensional-array adjacency-matrix

当我的输入如下:

11

Harry Kate Fred Carol

我的邻接矩阵应该让哈利[7] [7],凯特[7] [10],弗雷德[7] [5]和卡罗尔[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;
}

2 个答案:

答案 0 :(得分:1)

您的程序存在以下问题需要更正。

 //default constructor
    Element(void) 

构造函数应定义为

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

two dimensional array using vector in cpp

答案 1 :(得分:0)

在你的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
    }
}