Printing lists with commas C++

后端 未结 28 2150
时光取名叫无心
时光取名叫无心 2020-11-22 03:33

I know how to do this in other languages, but not C++, which I am forced to use here.

I have a Set of Strings that I\'m printing to out in a list, and they need a co

28条回答
  •  滥情空心
    2020-11-22 03:53

    My typical method for doing separators (in any language) is to use a mid-tested loop. The C++ code would be:

    for (;;) {
       std::cout << *iter;
       if (++iter == keywords.end()) break;
       std::cout << ",";
    }
    

    (note: An extra if check is needed prior to the loop if keywords may be empty)

    Most of the other solutions shown end up doing an entire extra test every loop iteration. You are doing I/O, so the time taken by that isn't a huge problem, but it offends my sensibilities.

提交回复
热议问题