Best Loop Idiom for special casing the last element

后端 未结 18 990
梦毁少年i
梦毁少年i 2020-12-23 09:25

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (

18条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 09:59

    Since your case is simply processing text, you don't need the conditional inside the loop. A C example:

    char* items[] = {"dog", "cat", "bat"};
    char* output[STRING_LENGTH] = {0};
    char* pStr = &output[1];
    int   i;
    
    output[0] = '[';
    for (i=0; i < (sizeof(items) / sizeof(char*)); ++i) {
        sprintf(pStr,"%s,",items[i]);
        pStr = &output[0] + strlen(output);
    }
    output[strlen(output)-1] = ']';
    

    Instead of adding a conditional to avoid generating the trailing comma, go ahead and generate it (to keep your loop simple and conditional-free) and simply overwrite it at the end. Many times, I find it clearer to generate the special case just like any other loop iteration and then manually replace it at the end (although if the "replace it" code is more than a couple of lines, this method can actually become harder to read).

提交回复
热议问题