Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to subsequence of a valarray considering it as a 2D matrix in C++

Tags:

c++

I'm learning C++, so please be patient with me. I have a std::valarray in which there are double elements and I consider it as a 2D matrix.

class Matrix {
    valarray<double> elems;
    int r, c;
public:
/* type? operator[](int r) { return ? } */
//...
}

I want to overload the operator[], so that I can get a row of the matrix, and after that, I want have the m[r][c] access operator.

Is there any way to get a row, as a sequence of double using std::slice in the valarray, so that if I change a value, it is changed also in the matrix?

I've read this definition in valarray:

std::slice_array<T> operator[]( std::slice slicearr );

My operator[] must have std::slice_array<double>& as returned type?

Thanks.

like image 545
Sam Avatar asked Nov 19 '18 15:11

Sam


1 Answers

I don't think std::slice and std::slice_array is what you're looking for, especially the latter is nothing but a helper type with a very limited public interface. You can instead return an proxy object. Here's a possible example of how to implement that.

class Matrix {
    /* ... */

    class RowProxy {
       public:
          RowProxy(std::valarray<double>& elems, int c, int row) :
              elems(elems), c(c), row(row) {}

          double& operator[](int j)
          {
             return elems[row*c + j];
          }

       private:
          std::valarray<double>& elems;
          int row;
          int c;
    };

    RowProxy operator[](int i)
    {
       return RowProxy(elems, c, i);
    }
};

This way, you can access the data with two operator[].

Matrix m(2, 4); // Assuming the ctor initializes elemens with row*column

m[0][0] = 1.234;
m[1][0] = 2.234;
m[1][3] = -52.023;

Note that both Matrix and RowProxy are missing overloads and proper handling for const-ness, and variable names are poor. Also, you might want to think about an out-of-bounds error handling strategy. But it may serve as a starting point for your implementation.

like image 174
lubgr Avatar answered Nov 19 '22 22:11

lubgr