Having some trouble finding the sum of a 2D vector. Does this look ok?
int sumOfElements(vector<iniMatrix> &theBlocks)
{
int theSum = 0;
for(unsigned i=0; (i < theBlocks.size()); i++)
{
for(unsigned j=0; (j < theBlocks[i].size()); j++)
{
theSum +=theBlocks[i][j];
}
}
return theSum;
}
It returns a negative number, however, it should return a positive number..
Hope someone can help 🙂
The code looks proper in an abstract sense, but you may be overflowing
theSum. You can try makingtheSumtypedoubleto see what value you get to help sort out the proper integral type to use for it.When you observe the returned value, you can see if it would fit in an
intor if you need to use a widerlongorlong longtype.If all the values in the matrix are positive, you should consider using one of the unsigned integral types. which would double your range of allowed values.