在C++中缩写 for 循环

Abreviating the for loop in C++

本文关键字:for 循环 缩写 C++      更新时间:2023-10-16

最近,在编码时,我发现自己一遍又一遍地编写完全相同的循环标头:

for (int i = 0; i < [somevalue]; i++)
{
    [other code]
}

有没有人知道一种方法来重载 for 循环,或者定义另一个关键字,以便它接受一个数字并通过给定的 for 循环将其馈送,将 for 缩写为如下所示的内容:

for ([somevalue])
{
    [other code]
}

nfor ([somevalue])
{
    [other code]
}

因为一直编写for(12)并让它遍历代码 12 次会更好

您可以创建自己的for方法,该方法采用函数对象:

template <class F>
void for_t(std::size_t n, F const& f)
{
    while (n--)
        f();
}
int main()
{
    int count = 0;
    for_t(5, [&] { std::cout << ++count << " "; });
}

或者使用范围(和提升):

for(int i : boost::counting_range(0, limit))
    /* do nice things */ ;

提升::counting_range

或者

,如果你想使用普通的旧宏,可以做

#define nfor(somevalue) for(int i = 0; i < somevalue; ++i)

然后将其用作

nfor(10)
{
    cout << "Hello World " << i << "!" << endl;
}
class until {
public:
    until(int limit) : count(limit) {}
    int operator*() const { return count; }
    until &operator++() { ++count; return *this; }
    bool operator!=(const until &rhs) const { return count != rhs.count; }
    until begin() const { return 0; }
    until end() const { return count; };
private:
    int count;
};
#include <iostream>
int main() {    
    for (int count : until(5)) {
        std::cout << count << ' ';
    }
}

N3853:基于范围的for-loops,下一代将使for更紧凑。

例如喜欢

template< class Func >
void repeat( int const n, Func const& f )
{
    for( int i = 1; i <= n; ++i ) { f(); }
}
void foo()
{
    int n = 1;
    repeat( 12, [&]
    {
        // other code, e.g.
        cout << n++ << endl;
    } );
}

免责声明:编译器的手未触及代码。

如果您喜欢宏方法,最好稍微调整一下@vsoftco的解决方案,以便为循环控制变量使用不同的名称:

#define nfor(varname, somevalue) for(int varname = 0; varname < somevalue; ++varname)

这样,您可以使用上面的宏嵌套 for 循环:

nfor(i, 10)
{
    nfor(j, 10)
    {
        cout << i << " " << j;
    }
}

这在 C++ 中的 for 循环中是不可能的。有两种方法可以做你想做的事。

第一种是使用 C++11 中引入的 for loop 系列的最新成员。

for(int x : (int[12]){}){
    // Do stuff
}

不是你想要的,但仍然短一点。另一种选择是创建自己的函数,并让它采用大小和函数。0x499602D2在这方面击败了我,所以请参阅他们的帖子了解如何做到这一点。