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

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

    You could use the STL together with a lambda expression.

    #include 
    #include 
    
    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 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.

提交回复
热议问题