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;
	}
}

I think your printing loop is incorrect, try doing this :

list<nonZero>::iterator j;
	list< list<nonZero> >::iterator i;
	for(i = rows.begin(); i != rows.end(); i++)
	{
		for(j = i->begin();j != i->end(); j++)
		{
			cout<<(*j).getColumn()<<" "<<(*j).getValue()<<" ";
		}
		cout<<endl;
	}
commented: Helped me out a lot +2

Also why not create noneZero object .??
Well its a matter of design.

The print statement was the problem, thanks a million first person. Also I needed to clear the list on line 53 to start with a fresh sublist each time

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.