delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/19/12:01:11

From: "Brock" <peabody AT npcinternational DOT com>
Newsgroups: comp.os.msdos.djgpp,comp.lang.c++
Subject: Re: 2d Matrix class with conventional c/c++ element access semantics
Date: Mon, 19 Jan 1998 11:04:56 -0600
Organization: ISPNews http://ispnews.com
Lines: 65
Message-ID: <6a00c4$qj$1@news4.ispnews.com>
References: <34C36C45 DOT 24966424 AT pentek DOT com>
NNTP-Posting-Host: pittport12.cjnetworks.com
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Charles Krug wrote in message <34C36C45 DOT 24966424 AT pentek DOT com>...
>I'd like to create a Matrix class with "drop-in" compatible accessor
>function semantics.

<<

>
>template<class T>
>matrix<T>
>protected:
>    vector<vector<T> > rows;
>
>public:
>    vector<T> operator [] (unsigned int i) {return rows[i];}

<<

>// now I can iterate through the entire matrix this way
>for (int i = 0; i < rows; ++i)
>    for (int j = 0; j < columns; ++j)
>        // I can access myMatrix[i][j] here
>
>But I crash in my matrix access.  Is there any way to do what I want?  I
>want to copy the interface semantics of the conventional array while
>adding type safety.  I could, of course, use the () operator for both
>indices, but that would defeat my objective, which is to graft this
>class into existing code with minimal complication.

Maybe you are crashing because you are not dimensioning all the row vectors
to the proper size(the number of columns) in the constructor.

template <class T> class matrix {
public:

    // these typedefs will come in handy for you later

    typedef std::vector<T>                 row_type;
    typedef std::vector<row_type>    matrix_type;

        // use vector<>'s constructor to initialize each row with a vector
of the proper size

    matrix(int num_rows, int num_cols) : the_matrix_(num_rows,
row_type(num_cols)) {}

private:

    matrix_type the_matrix_;
};


>
>ALSO--should by row vector be a vector of <T> or a vector of pointers to
><T>?


No, if you want a vector of pointers to T, use something like:

matrix<int*> matrix_of_pointers(3,3);

Maybe you should check out the valarray class, I don't know much about it,
but it may provide you with a better solution.


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019