2

C++ 新手,我被要求在我的Matrix类中创建一个函数,该函数返回对 spot 中值的引用(i,j)

作为分配的一部分,该类包含一个表示矩阵的arrayof :std::list

list <value_type> * m_val;

这没有多大意义,但是,这就是任务。我被告知要开始使用这个:

template <class E>
inline E& Matrix<E>::operator() (unsigned i, unsigned j) {

}

这是我尝试过的:

template <class E>
inline E& Matrix<E>::operator() (unsigned i, unsigned j) {
    list<value_type> row = m_val[i];    // Get the row
    typename list< E >::iterator it = row.begin();  // Iterator at beginning of row
    for (int x = 0; x < j; ++x) {
        ++it; // For each column, I increase the iterator until I reach the desired spot
    }


    return *it;   // I'm confused here. I got my iterator in the right spot, but I am not sure how to return a reference to its value.
}

但据我所知,这会返回值,而不是引用。我想要实现的基本上是

myMatrix(2,3) = 50;   // Now the value at 2,3 is 50.
4

1 回答 1

1

list <value_type> * m_val;

这看起来不太好。如果您已经在使用标准容器,为什么不使用std::vector < list<value_type >or std::array < list<value_type> >

除此之外:

template <class E>
inline E& Matrix<E>::operator() (unsigned i, unsigned j) {
    // less error-prone with bounds-checking, as Remy Lebeau stated in a 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];    // this would copy the list
    list<value_type>& row = m_val[i];

    typename list<value_type>::iterator it = row.begin();

    // less error-prone with bounds-checking, as Remy Lebeau stated in a comment
    if(j >= row.size())
    {
        throw std::out_of_range("second index out of range");
    }

    std::advance(it, j);

    return *it;   // correct :) `*it` returns a `value_type&`
}

但是,边界检查不是强制性的 - 如果您不检查,请确保记录它(并指出它!)。

我宁愿使用Evalue_type始终如一。

C++11 单行:

template < class E >
inline E& Matrix<E>::operator() (unsigned i, unsigned j)
{
    return std::next( m_val[i].begin(), j );
}
于 2013-05-14T00:55:14.147 回答