Is there an equivalent to the range-based `enumerate` loop from python in modern C++?

后端 未结 9 1309
终归单人心
终归单人心 2020-12-21 00:48

Is there an equivalent to the range-based enumerate loop from python in C++? I would imagine something like this.

enumerateLoop (auto counter, a         


        
9条回答
  •  长情又很酷
    2020-12-21 01:31

    Here's a macro-based solution that probably beats most others on simplicity, compile time, and code generation quality:

    #include 
    
    #define fori(i, ...) if(size_t i = -1) for(__VA_ARGS__) if(i++, true)
    
    int main() {
        fori(i, auto const & x : {"hello", "world", "!"}) {
            std::cout << i << " " << x << std::endl;
        }
    }
    

    Result:

    $ g++ -o enumerate enumerate.cpp -std=c++11 && ./enumerate 
    0 hello
    1 world
    2 !
    

提交回复
热议问题