c++ - 基于范围的 for 循环,第一项的特殊情况

标签 c++ for-loop c++11 range-based-loop

我发现自己经常使用如下代码:

bool isFirst = true;
for(const auto &item: items)
{
    if(!isFirst) 
    { 
       // Do something
    }
    // Normal processing
    isFirst = false;
}

似乎应该有更好的方式来表达这一点,因为它是函数中的一种常见模式,就像“连接”一样。

最佳答案

也许 for_first_then_each 是您正在寻找的?它根据迭代器获取您的范围,并将第一个函数应用于第一个元素,将第二个函数应用于其余元素。

#include <iostream>
#include <vector>

template<typename BeginIt, typename EndIt, typename FirstFun, typename OthersFun>
void for_first_then_each(BeginIt begin, EndIt end, FirstFun firstFun, OthersFun othersFun) {
    if(begin == end) return;
    firstFun(*begin);
    for(auto it = std::next(begin); it != end; ++it) {
        othersFun(*it);
    };
} 

int main() {

    std::vector<int> v = {0, 1, 2, 3};

    for_first_then_each(v.begin(), v.end(),
        [](auto first) { std::cout << first + 42 << '\n'; },
        [](auto other) { std::cout << other - 42 << '\n'; }
    );

    // Outputs 42, -41, -40, -39

    return 0;
}

关于c++ - 基于范围的 for 循环,第一项的特殊情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831971/

相关文章:

c++ - 为 C 或 C++ 定义的通用预处理器?

java - Java 满足条件后停止循环

c++ - 防止为非常量对象调用 const 函数

c++ - 返回一个空对象而不是对 vector 的引用

c++ - 如何让列表可以隐式转换为我的类对象?

c++ - 为什么派生类中的重写函数会隐藏基类的其他重载?

c++ - 中断 accept()

c++ - QUdpSocket 与 ShareAddress 的多播绑定(bind)失败

c - 在 C 中使用不同的数值为相同的操作获取不同的长度

java - 对于循环错误,我该如何解决这个问题?