迭代器在std :: list中的最后一个元素

cpx*_*cpx 51 c++ stl

#include <list>
using std::list;

int main()
{
    list <int> n;
    n.push_back(1);
    n.push_back(2);
    n.push_back(3);

    list <int>::iterator iter = n.begin();
    std::advance(iter, n.size() - 1); //iter is set to last element
}
Run Code Online (Sandbox Code Playgroud)

有没有其他方法让列表中的最后一个元素?

CB *_*ley 89

是的,你可以从最后回来.(假设您知道列表不为空.)

std::list<int>::iterator i = n.end();
--i;
Run Code Online (Sandbox Code Playgroud)


Rem*_*eau 59

以下任一项都将返回std::list<int>::iterator到以下内容中的最后一项list:

std::list<int>::iterator iter = n.end();
--iter;
Run Code Online (Sandbox Code Playgroud)

std::list<int>::iterator iter = n.end();
std::advance(iter, -1);
Run Code Online (Sandbox Code Playgroud)

// C++11
std::list<int>::iterator iter = std::next(n.end(), -1);
Run Code Online (Sandbox Code Playgroud)

// C++11
std::list<int>::iterator iter = std::prev(n.end());
Run Code Online (Sandbox Code Playgroud)

以下将返回std::list<int>::reverse_iterator到最后一项list:

std::list<int>::reverse_iterator iter = std::list::rbegin();
Run Code Online (Sandbox Code Playgroud)


Eug*_*nca 10

使用反向迭代器:

iter = (++n.rbegin()).base()
Run Code Online (Sandbox Code Playgroud)

作为旁注:这个或Charles Bailey方法具有恒定的复杂性,而std::advance(iter, n.size() - 1);与list具有线性复杂性[因为它具有双向迭代器].


Mit*_*n.O 6

拿走end()并向后走.

list <int>::iterator iter = n.end();
cout << *(--iter);
Run Code Online (Sandbox Code Playgroud)


Mey*_*sam 5

std::list<int>::iterator iter = --n.end();
cout << *iter;
Run Code Online (Sandbox Code Playgroud)

  • 右值迭代器上的前缀运算符仅在某些情况下有效,并且不是必需的,因此您应该使用“std::prev()”;请参阅/sf/ask/187472281/#comment91853941_2678214 (2认同)