Get index in C++11 foreach loop

后端 未结 5 871
太阳男子
太阳男子 2020-12-28 12:55

Is there a convenient way to get the index of the current container entry in a C++11 foreach loop, like enumerate in python:

for idx, obj in enu         


        
5条回答
  •  温柔的废话
    2020-12-28 13:50

    What about a simple solution like:

    int counter=0;
    for (auto &val: container)
    {
        makeStuff(val, counter);
    
        counter++;
    }
    

    You could make a bit more "difficult" to add code after the counter by adding a scope:

    int counter=0;
    for (auto &val: container)
    {{
        makeStuff(val, counter); 
    }counter++;}
    

    As @graham.reeds pointed, normal for loop is also a solution, that could be as fast:

    int counter=0;
    for (auto it=container.begin(); it!=container.end(); ++it, ++counter)
    {
        makeStuff(val, counter);
    }
    

    And finally, a alternative way using algorithm:

    int counter = 0;
    std::for_each(container.begin(), container.end(), [&counter](int &val){ 
        makeStuff(val, counter++);
    });
    

    Note: the order between range loop and normal loop is guaranteed by the standard 6.5.4. Meaning the counter is able to be coherent with the position in the container.

提交回复
热议问题