You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取仅支持前向遍历的容器的最后元素的前向迭代器?

获取前向遍历容器最后一个元素的便捷方法

你当前的方法虽然可行,但std::distance会先遍历整个容器一次,std::advance又会再遍历一次,做了两次O(n)的操作。下面提供更高效或更简洁的替代方案:

标准库原生优化写法

只需要一次遍历就能定位到最后一个元素,逻辑更直观:

const std::forward_list<int> list{1, 2, 3, 4, 5};
auto it = list.cbegin();
if (it != list.cend()) {
    while (std::next(it) != list.cend()) {
        ++it;
    }
    std::cout << *it << std::endl;
}

核心思路是:一直移动迭代器,直到它的下一个位置是容器末尾,此时当前迭代器就指向最后一个元素。

Boost库便捷写法

如果允许使用Boost,Boost.Range提供的boost::last可以直接获取范围的最后一个元素,内部会自动处理前向迭代器的遍历逻辑:

#include <boost/range/algorithm.hpp>

const std::forward_list<int> list{1, 2, 3, 4, 5};
// 若容器为空,boost::last会抛出std::out_of_range异常,可提前判断!list.empty()
std::cout << boost::last(list) << std::endl;

这个写法最简洁,不需要手动编写循环逻辑。

内容的提问来源于stack exchange,提问作者Kaiyakha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:24:57