Printing lists with commas C++

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

    There is a little problem with the ++ operator you are using.

    You can try:

    if (++iter != keywords.end())
        out << ", ";
    iter--;
    

    This way, ++ will be evaluated before compare the iterator with keywords.end().

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 04:06

    I would go with something like this, an easy solution and should work for all iterators.

    int maxele = maxele = v.size() - 1;
    for ( cur = v.begin() , i = 0; i < maxele ; ++i)
    {
        std::cout << *cur++ << " , ";
    }
    if ( maxele >= 0 )
    {
      std::cout << *cur << std::endl;
    }
    
    0 讨论(0)
  • 2020-11-22 04:07

    Can use functors:

    #include <functional>
    
    string getSeparatedValues(function<bool()> condition, function<string()> output, string separator)
    {
        string out;
        out += output();
        while (condition())
            out += separator + output();
        return out;
    }
    

    Example:

    if (!keywords.empty())
    {
        auto iter = keywords.begin();
        cout << getSeparatedValues([&]() { return ++iter != keywords.end(); }, [&]() { return *iter; }, ", ") << endl;
    }
    
    0 讨论(0)
提交回复
热议问题