Matrix manipulation

May 8, 2011 at 12:31am
I have a function with the following prototype:

1
2
3
void replaceZero(int matrix[][N]){

}


I want to get the number of rows in this matrix. Is it possible to do that in C++?
May 8, 2011 at 12:47am
Not with standard arrays. You have to pass the dimension(s) of the array as (an) additional parameter(s).
May 9, 2011 at 3:17pm
hmm..thanks. that's what I was thinking. just curious. how is java able to do it or it can't? i.e matrix[0].length ..
May 9, 2011 at 5:23pm
Arrays are objects in Java, so the Array type can have a member length that internally stores how long it is. If you want something like that in C++, you could look into std::vector or one of the other standard containers.
May 9, 2011 at 5:52pm
Although the correct answer has already been given by Zhuge I would like to point out that you have the option to overload the "[]" operator in C++ and create a Java like object in C++. You just have to be the one to define everything, it isn't done for you.
May 19, 2011 at 8:29pm
Thanks.
May 20, 2011 at 2:08am
If you don't have too many different types of matrices (with different dimensions), you could use templates to generate a function for each matrix:

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
#include <iostream>
using namespace std;

template <typename T, size_t M, size_t N>
void zero_matrix( T (&matrix)[ M ][ N ] )
  {
  for (size_t m = 0; m < M; m++)
  for (size_t n = 0; n < N; n++)
    matrix[ m ][ n ] = 0;
  }

template <typename T, size_t M, size_t N>
void print_matrix( T (&matrix)[ M ][ N ] )
  {
  for (size_t m = 0; m < M; m++)
    {
    for (size_t n = 0; n < N; n++)
      cout << matrix[ m ][ n ] << " ";
    cout << endl;
    }
  }

int main()
  {
  int    A[ 3 ][ 4 ];
  double B[ 2 ][ 5 ];

  zero_matrix( A );
  zero_matrix( B );

  cout << "A:\n";
  print_matrix( A );

  cout << "\nB:\n";
  print_matrix( B );

  return 0;
  }
Topic archived. No new replies allowed.