Out of Range Vector Matrix

I'm trying to create a bool function that returns true only when the number of rows in the matrix == 1 or if there are more that 2 rows, it returns true if each row as the same number of elements. My problem is with an example vector like below, I get and out of range error. Using Linux g++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int num_rows(const Matrix& m) 
{     
  return m.size();
}

typedef vector<vector<double>> Matrix;

//Example Matrix
Matrix A = 
    {
      {  0,   2,  0, -2},
      {  2,   0,  1,  0, 1.6},
      {  0,   1,  0,  1,   0},
      { -2,   0,  1,  0,   0},
      {2.5, 1.6,  0,  0,   0}
    };

//Function with error
bool is_matrix(const Matrix& m) 
{
    //returns false if there are 0 rows
    if (num_rows(m) < 1)
    {
        return false;
    }
    //if 2 or more rows..
    else if (num_rows(m) >= 2)
    {
        //check the number of elements in each row
        for (int i = 1; i < num_rows(m); i++)
        {
            //if at any point the number of elements are not equal return false
            if (m[i].size() != m[i-1].size())
            {
                return false;
            }
        }
    }
    //only other case is where num_rows(m) == 1 in this case just return true
    return true;
}     

Last edited on
Can you post the definition of the Matrix class, plus at least num_rows()?
Sorry. I completely forgot.
1
2
3
4
5
6
7
int num_rows(const Matrix& m) 
{     
  return m.size();
}

typedef vector<vector<double>> Matrix;
Doesn't crash for me and I don't see any errors. (Zhuge might be able to prove me wrong there).

Can you post your entire code or upload it somewhere?
My full code is here:
http://codeviewer.org/view/code:5168

After some commenting out the function in the cout portion of my linked code it seems like the bool is_matrix is not actually the one causing the issue. Now I just need to find out whats going on. Some more help would be great, I've been at this for a couple hours.

EDIT: I think error is in my sparsity funciton. Trying to figure it out now.
Last edited on
Yes, you are getting out of range errors in the sparsity and degree functions.

1
2
3
4
5
6
7
8
9
10
11
12
    double zero_counter = 0;

	for (int i = 0; i < num_rows(m); i++)
	{
		for (int j = 0; j < num_rows(m); j++)
		{
			if (m[i].at(j) == 0)
			{
				zero_counter++;
			}
		}
	}


You can't use num_rows for both dimensions of the matrix, you should be using num_cols somewhere. The second loop should be something like for (int j = 0; j < m[i].size(); j++)

Or you can use your own num_cols as long as you know it's going to be the same number for every column.
Last edited on
Thank you very much. I had tunnel vision and I really thought that the is_matrix was the problem.
Topic archived. No new replies allowed.