简体   繁体   English

STL列表访问倒数第二个元素

[英]STL list access to next-to-last element

How do I get an iterator to the next-to-last element in a STL list without creating a temporary and modifying the list? 如何在不创建临时列表和修改列表的情况下使迭代器到达STL列表中的倒数第二个元素? Is it possible to just say: --(--mylist.end()) ? 是否可以只说: --(--mylist.end()) Or would this change the end iterator of the list due to the prefix decrement? 还是会由于前缀的减少而改变列表的end迭代器?

Please note that in general, --mylist.end() is not guaranteed to compile for every container. 请注意,通常,-- --mylist.end()不能保证为每个容器编译。

For example, if you use a std::vector or std::array in release mode, mylist.end() is probably a raw pointer, and you cannot decrement a pointer returned by value from a function. 例如,如果在发布模式下使用std::vectorstd::array ,则mylist.end()可能是原始指针,并且无法递减由函数值返回的指针。

A generic solution to this problem in C++11 is std::prev(std::prev(mylist.end())) , after checking that the list is long enough, of course. 当然,在检查列表足够长之后,C ++ 11中针对此问题的通用解决方案是std::prev(std::prev(mylist.end())) You need to #include <iterator> for this. 您需要为此#include <iterator>

You could use std::advance and a reverse_iterator: 您可以使用std :: advance和reverse_iterator:

SomeContainerType::reverse_iterator it = myList.rbegin();
std::advance(it, 1); // next to last element

This works even if the iterator type in question does not support operator+ . 即使有问题的迭代器类型不支持operator+

如果使用reverse_iterator ,则: some_list.rbegin() + 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM