Question

I just wanted to know how to overload the operator [] to acces a matrix within a class, and I found how to that here. But, I have a question about this: Which way of changing a matrix will be more efficient?

1: Overloading the operator []: (code extracted from the previous link)

class CMatrix {
public:
   int rows, cols;
   int **arr;

public:

   int* operator[]( int const y )
   {
      return &arr[0][y];
   }

   ....

Edit: I relied too much on the other example: Should it work this way?

   int* operator[]( int const x )
   {
      return &arr[x];
   }

2:Using a "normal" method:

class CMatrix {
public:
   int rows, cols;
   int **arr;

public:
   void changematrix( int i, int j, int n)
   {
      arr[i][j]=n;
   }
...

Edit: Fixed const on changematrix

Was it helpful?

Solution

Write correct, readable code and let the compiler worry about efficiency.

If you have performance problems, and if when you run a profiler to measure the performance (which you MUST do before trying to optimize) this code shows up as a performance issue, then you can:

1) Examine the assembly language interpretation of the code generated by the compiler with full optimization enabled, or

2) Try it both ways, measure, and pick the faster one.

The results will be highly dependent on the compiler you are using and the flags you specify for that compiler.

OTHER TIPS

Neither method will work as you have declared

 int **arr;

gives no row length information for:

  return &arr[0][y];
  arr[i][j]=n;

I would go for a third option, using operator() instead of operator[]:

int& operator()(size_t i, size_t j) {
    return arr[i][j];
}
int operator()(size_t i, size_t j) const {
    return arr[i][j];
}

The user will then do:

CMatrix m = ...
m(1,2) = 5;
std::cout << m(1,2);

Other than that, I would really consider whether the way of laying out the data internally the the most efficient. Is this a jagged array? Or do all rows have the same width? If this represents a rectangle shaped array (i.e. all rows have the same number of columns) you might be better off storing all elements in a single 1D array, and using some basic arithmetic to locate the correct element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top