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

如何基于条件用C++标准库正向/反向遍历vector指定元素?

解决C++根据条件遍历vector前/后N个元素的标准库方案

方法1:统一使用正向迭代器范围

直接通过计算迭代器位置,把“后size个元素”转换成正向迭代器的范围,用同一种迭代器类型调用标准库算法,避开反向迭代器的类型冲突问题。

比如用std::for_each遍历的示例:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    const std::vector<int> vec = {1,2,3,4,5,6,7,8,9};
    const bool b_condition = false; // true遍历前3个,false遍历后3个
    const size_t size = 3;

    // 提前做边界检查,避免越界
    if (size > vec.size()) {
        return 1;
    }

    auto start = b_condition ? vec.begin() : vec.end() - size;
    auto end = b_condition ? vec.begin() + size : vec.end();

    std::for_each(start, end, [](int val) {
        std::cout << val << " ";
    });
    // b_condition为false时输出:7 8 9
    return 0;
}

方法2:封装核心逻辑,分分支调用算法

如果偏好反向迭代器的写法,可以把遍历逻辑封装成可调用对象,在不同分支里分别用正向/反向迭代器调用算法,复用核心处理逻辑:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    const std::vector<int> vec = {1,2,3,4,5,6,7,8,9};
    const bool b_condition = true;
    const size_t size = 3;

    if (size > vec.size()) {
        return 1;
    }

    auto process_val = [](int val) { std::cout << val << " "; };

    if (b_condition) {
        std::for_each(vec.begin(), std::next(vec.begin(), size), process_val);
    } else {
        std::for_each(vec.rbegin(), std::next(vec.rbegin(), size), process_val);
    }
    // b_condition为true时输出:1 2 3
    return 0;
}

std::next可以安全移动迭代器,适配所有迭代器类型,比直接加减更通用。

方法3:C++20用std::span统一子范围

C++20引入的std::span能创建容器的子视图,不管是前N个还是后N个元素,span的迭代器都是正向且类型一致,写法更简洁安全:

#include <vector>
#include <algorithm>
#include <iostream>
#include <span>

int main() {
    const std::vector<int> vec = {1,2,3,4,5,6,7,8,9};
    const bool b_condition = false;
    const size_t size = 3;

    if (size > vec.size()) {
        return 1;
    }

    std::span<const int> sub_span = b_condition 
        ? std::span(vec.begin(), size) 
        : std::span(vec.end() - size, size);

    // 也可以用C++20范围算法:std::ranges::for_each(sub_span, process_val);
    std::for_each(sub_span.begin(), sub_span.end(), [](int val) {
        std::cout << val << " ";
    });
    // b_condition为false时输出:7 8 9
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:52:36