Re: Good or bad code?
In article <49b3bb4d$0$90265$14726298@news.sunsite.dk>,
"mlt" <asdf@asd.com> wrote:
I am writing a function that takes a reference P to a
std::vector<std::vector<int> >. Before calling this function I don't know
the dimensions of P. I need to define those in the function and I need to
read form all elements in P.
Here is some sample code:
http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.10
However, I suggest you use a vector internally, like this:
class BadIndex : public std::logic_error { };
template < typename T >
class?Matrix
{
public:
Matrix(unsigned?rows,?unsigned?cols)
: rows_(rows)
, cols_(cols)
, data_(rows * cols)
{
if?(rows?==?0?||?cols?==?0)
throw?BadIndex("Matrix?constructor?has?0?size");
}
???T&?operator()?(unsigned?row,?unsigned?col)
{
if?(row?>=?rows_?||?col?>=?cols_)
throw?BadIndex("Matrix?subscript?out?of?bounds");
return?data_[cols_*row?+?col];
}
???T??operator()?(unsigned?row,?unsigned?col)?const
{
if?(row?>=?rows_?||?col?>=?cols_)
throw?BadIndex("Matrix?subscript?out?of?bounds");
return?data_[cols_*row?+?col];
}
// other member-functions to taste
?private:
???unsigned?rows_,?cols_;
???std::vector<T>?data_;
?};
?
But is this how it should be done? Seems a bit clumsy to me.
It's still a bit clumsy... It would be nice to have some iterators and
some resize functions.