簡體   English   中英

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

[英]Returning a reference of an std::list element from its iterator

C ++的新手,我被要求在Matrix類中創建一個函數,該函數返回對(i,j)點值的引用。

作為分配的一部分,該類包含一個std::list array來表示Matrix:

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.

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一線式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM