How to use std::foreach with parameters/modification

前端 未结 6 2301
难免孤独
难免孤独 2020-12-23 11:34

I\'ve found myself writing

for(int i=0;iDoWhatever(param);

a lot, and I\'d like to compress this into

6条回答
  •  渐次进展
    2020-12-23 12:08

    If you are using GCC you can define something like:

    #define foreach(element, array) \
        for(typeof((array).begin()) element = (array).begin(), __end_##element = (array).end();\
            element != __end_##element;\
            ++element)
    

    and use it after like this:

    foreach(element, array){
        element->DoSomething(); //or (*element)->DoSomething() if type is already a pointer
    }
    

    I use this on a custom array but it works fine with std::vector too.

提交回复
热议问题