Access index in range-for loop

后端 未结 6 482
忘了有多久
忘了有多久 2020-12-24 11:44

I have a vector of objects and am iterating through it using a range-for loop. I am using it to print a function from the object, like this:

vector

        
6条回答
  •  眼角桃花
    2020-12-24 12:13

    I created a preprocessor macro (greatly simplified by @Artyer) that handles this for you in a relatively clean way:

    #define for_indexed(...) for_indexed_v(i, __VA_ARGS__)
    #define for_indexed_v(v, ...) if (std::size_t v = -1) for (__VA_ARGS__) if ((++v, true))
    

    Example usage:

    std::vector v{1, 2, 3};
    for_indexed (auto const& item : v) {
        if (i > 0) std::cout << ", ";
        std::cout << i << ": " << item;
    }
    

    To use a different loop variable:

    for_indexed_v (my_counter, auto const& item : v) ...
    

    The extra control flow logic should be optimized away in any non-debug builds. You're left with a relatively easy-to-read loop syntax.

    2020 note: It would probably be more wise to use a lambda-based solution instead of macro trickery. Of course, the syntax wouldn't be as "clean", but it would have the advantage of being recognizable as actual C++ syntax. The choice is yours.

    Update 2017/05/28: Made break; statements work correctly
    Update 2019/01/28: Put for in the macro name so that the word indexed is a valid variable name. I doubt for_indexed will cause any conflicts.
    Update 2020/12/23: Simplified drastically (thanks @Artyer)

提交回复
热议问题