When my input looks like this:
11
Harry Kate Fred Carol
My adjacency matrix should put Harry at [7][7], Kate at [7][10], Fred at [7][5], and Carol at [7][2]. However, Carol & Kate get inserted at other locations within the adj. matrix as well. I am guessing this has something to do with stack and heap memory, but I am not sure how to find the bug. Using cout statements, there doesn't appear to be any issues.
Code below
#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;
}