I have a 2D array class that is actually mapped to a 1D vector. For example, to obtain an element at a particular position, the code is as follows:
template <typename T>
T mat <T>::at(const size_t &row, const size_t &col) const
{
return m_values[row*ncol() + col];
}
Here's the relevant section of the class in-context:
template <typename T>
class mat
{
private:
std::vector <T> m_values;
size_t m_nrow, m_ncol;
public:
mat();
size_t ncol() const{ return m_ncol; };
size_t nrow() const{ return m_nrow; };
T at(const size_t &row, const size_t &col) const;
std::vector <T> row(const size_t &row) const;
std::vector <T> col(const size_t &col) const;
};
m_nrow
and m_ncol
contain the number of rows and columns of the 2D array, respectively, while m_values
contains the values of the array. They're assigned in another (long) constructor.
I now need to be able to return an entire row or column. Here's how that's currently implemented:
template <typename T>
std::vector <T> mat <T>::row(const size_t &row) const
{
std::vector <T> tmp;
for(size_t j=0; j < ncol(); j++)
{
tmp.push_back(at(row, j));
}
return tmp;
}
template <typename T>
std::vector <T> mat <T>::col(const size_t &col) const
{
std::vector <T> tmp;
for(size_t i=0; i < nrow(); i++)
{
tmp.push_back(at(i, col));
}
return tmp;
}
These implementations are easy to reason about but not particularly efficient: there's the pushing back to a temporary vector and the repeated calculation of row*ncol()
in at()
. Is there a more idiomatic way of doing this in C++11?
m_values
? What ismat
? What arencol()
andnrow()
? These are very relevant. Stub code is off-topic here. \$\endgroup\$