Printing lists with commas C++

后端 未结 28 1777
时光取名叫无心
时光取名叫无心 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

    There are lots of clever solutions, and too many that mangle the code beyond hope of salvation without letting the compiler do its job.

    The obvious solution, is to special-case the first iteration:

    bool first = true;
    for (auto const& e: sequence) {
       if (first) { first = false; } else { out << ", "; }
       out << e;
    }
    

    It's a dead simple pattern which:

    1. Does not mangle the loop: it's still obvious at a glance that each element will be iterated on.
    2. Allows more than just putting a separator, or actually printing a list, as the else block and the loop body can contain arbitrary statements.

    It may not be the absolutely most efficient code, but the potential performance loss of a single well-predicted branch is very likely to be overshadowed by the massive behemoth that is std::ostream::operator<<.

提交回复
热议问题