c++ - Returning a reference of an std::list element from its iterator -
new c++, i've been asked make function in matrix
class returns reference value in spot (i,j)
.
as part of assignment, class holds array
of std::list
represent matrix:
list <value_type> * m_val;
which doesn't make sense, well, that's assignment. told start working this:
template <class e> inline e& matrix<e>::operator() (unsigned i, unsigned j) { }
this tried:
template <class e> inline e& matrix<e>::operator() (unsigned i, unsigned j) { list<value_type> row = m_val[i]; // row typename list< e >::iterator = row.begin(); // iterator @ beginning of row (int x = 0; x < j; ++x) { ++it; // each column, increase iterator until reach desired spot } return *it; // i'm confused here. got iterator in right spot, not sure how return reference value. }
but far can tell, returns value, not reference. want achieve essentially
mymatrix(2,3) = 50; // value @ 2,3 50.
list <value_type> * m_val;
this doesn't good. if you're using standard containers, why not use std::vector < list<value_type >
or std::array < list<value_type> >
?
apart that:
template <class e> inline e& matrix<e>::operator() (unsigned i, unsigned j) { // less error-prone bounds-checking, remy lebeau stated in comment if(i >= size_of_m_val_array) { throw std::out_of_range("first index out of range"); } //list<value_type> row = m_val[i]; // copy list list<value_type>& row = m_val[i]; typename list<value_type>::iterator = row.begin(); // less error-prone bounds-checking, remy lebeau stated in comment if(j >= row.size()) { throw std::out_of_range("second index out of range"); } std::advance(it, j); return *it; // correct :) `*it` returns `value_type&` }
bounds-checking isn't mandatory, though - sure document (and point out!) if don't check.
i'd rather use e
or value_type
consistently.
c++11 one-liner:
template < class e > inline e& matrix<e>::operator() (unsigned i, unsigned j) { return std::next( m_val[i].begin(), j ); }
Comments
Post a Comment