From: "Brock" 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 Precedence: bulk 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 >matrix >protected: > vector > rows; > >public: > vector 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 matrix { public: // these typedefs will come in handy for you later typedef std::vector row_type; typedef std::vector 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 or a vector of pointers to >? No, if you want a vector of pointers to T, use something like: matrix 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.