Printing lists with commas C++

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

    It's very easy to fix that (taken from my answer here):

    bool print_delim = false;
    for (auto iter = keywords.begin(); iter != keywords.end( ); iter++ ) {
        if(print_delim) {
            out << ", ";
        }
        out << *iter;
        print_delim = true;
    }
    out << endl;
    

    I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:

    empty output
    firstIteration = true
    foreach item in list
        if firstIteration
            add delimiter to output
        add item to output
        firstIteration = false
    

    In some cases one could even omit the firstIteration indicator variable completely:

    empty output
    foreach item in list
        if not is_empty(output)
            add delimiter to output
        add item to output
    

提交回复
热议问题