Hi all,
I have a programming assignment to store sparse matrices using a list<list <myclass> >. I have pretty much everything nailed down but I'm going wrong at some point, the output is incorrect. Instead of giving me 4 lines with the column position and value of non zero values on each line I am getting 4 copies of all the values in a single line. Can anyone spot the issue? I'm assuming it's the way I'm attempting to store the lines in the nested while loops. I want to end up with a list of sublists, each of the sublists is a representation of the non-zero values of a matrix line.
Code follows, please note #include and using omitted to save space. The issue is, I think, somewhere between lines 44 - 54. Many thanks in advance.
tested input -
0 1 2 3
3 0 2 1
4 5 0 6
expected output -
2 1 3 2 4 3
1 3 3 2 4 1
1 4 2 5 4 6
Actual output -
2 1 3 2 4 3 1 3 3 2 4 1 1 4 2 5 4 6
2 1 3 2 4 3 1 3 3 2 4 1 1 4 2 5 4 6
2 1 3 2 4 3 1 3 3 2 4 1 1 4 2 5 4 6
2 1 3 2 4 3 1 3 3 2 4 1 1 4 2 5 4 6
class nonZero{
private:
int columnNo;
float valueContained;
public:
nonZero (int column, float value)
{
columnNo = column;
valueContained = value;
}
nonZero(){}
int getColumn()
{
return columnNo;
}
float getValue()
{
return valueContained;
}
};
int main(int argc, char *argv[])
{
double epsilon = 0;
list<nonZero> row;
list< list<nonZero> > rows;
if (argc > 1 && string(argv[1]) == "-e")
{
epsilon = fabs(strtod(argv[2], 0));
}
string line;
double value;
while(getline(cin, line))
{
std::istringstream lstream(line);
int itemNumber = 0;
while(lstream >> value)
{
itemNumber++;
if(value != 0 && fabs(value) > epsilon)
{
row.push_back(nonZero(itemNumber, value));
}
}
rows.push_back(row);
}
list<nonZero>::iterator j;
list< list<nonZero> >::iterator i;
for(i = rows.begin(); i != rows.end(); i++)
{
for(j = row.begin();j != row.end(); j++)
{
cout<<(*j).getColumn()<<" "<<(*j).getValue()<<" ";
}
cout<<endl;
}
}