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

前端 未结 10 1042
轮回少年
轮回少年 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:24

    There may be a way to do it but I very much doubt it would be more elegant. What you have in that first loop is already the correct way to do it, limiting the scope/lifetime of the loop variable.

    I would simply ignore the unused variable warning (it's only an indication from the compiler that something may be wrong, after all) or use the compiler facilities (if available) to simply turn off the warning at that point.

    This may be possible with some sort of #pragma depending on your environment, or some implementations allow you to do things like:

    for (int x = 0; x < 10; ++x) {
        (void)x;
    
        // Other code goes here, that does not reference "x".
    }
    

    I've seen that void trick used for unused parameters in function bodies.

    0 讨论(0)
  • 2020-12-24 05:25

    You could use the STL together with a lambda expression.

    #include <algorithm>
    #include <iostream>
    
    int main() {
        int a[] = {1,2,3,4,5,6};
    
        std::for_each(std::begin(a),
                std::end(a),
                [](int){std::cout << "Don't care" << std::endl;});
    }
    

    This approach also works for arbitrary containers such as vectors or lists. Let vector<int> a, then you'd call a.begin() and a.end(). Note that you can also use a function pointer instead of a lambda expression.

    The above preserves your notion of using a foreach, while not complaining about an unused parameter.

    0 讨论(0)
  • 2020-12-24 05:30

    In my opinion you misuse the range-based loop. The range-based loop should be used when the logic is: "for each element in the collection do something". The whole idea is to get rid of the index variable since it isn't important. If you have a collection, you should instrument it with the necessary APIs to enable range-based iteration. If you don't have a collection, you have no business to use range-based loop (actually, that's what the compiler implies in not-so-informative way). In this situation a normal for/while loop is the natural choice.

    0 讨论(0)
  • 2020-12-24 05:31

    Edit now with 100% fewer loop variables declared.

    template <typename F>
    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

    0 讨论(0)
提交回复
热议问题