C++11 range-based for loops without loop variable

前端 未结 10 1040
轮回少年
轮回少年 2020-12-24 04:33

In C++ I need to iterate a certain number of times, but I don\'t need an iteration variable. For example:

for( int x=0; x<10; ++x ) {
    /* code goes her         


        
10条回答
  •  礼貌的吻别
    2020-12-24 05:31

    Edit now with 100% fewer loop variables declared.

    template 
    void repeat(unsigned n, F f) {
        while (n--) f();
    }
    

    Use it as:

    repeat(10, f);
    

    or

    repeat(10, [] { f(); });
    

    or

    int g(int);
    repeat(10, std::bind(g, 42));
    

    See it live at http://ideone.com/4k83TJ

提交回复
热议问题