从其迭代器返回std :: list元素的引用

时间:2013-05-14 00:43:24

标签: c++

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

作为作业的一部分,该班级持有array 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.

1 个答案:

答案 0 :(得分:1)

list <value_type> * m_val;

这看起来不太好。如果您已使用标准容器,为什么不使用std::vector < list<value_type >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 one-liner:

template < class E >
inline E& Matrix<E>::operator() (unsigned i, unsigned j)
{
    return std::next( m_val[i].begin(), j );
}