std::list iterator: get next element

前端 未结 6 1758
情书的邮戳
情书的邮戳 2021-02-08 21:59

I\'m trying to build a string using data elements stored in a std::list, where I want commas placed only between the elements (ie, if elements are {A,B,C,D} in list, result stri

6条回答
  •  悲&欢浪女
    2021-02-08 22:41

    You cannot do it + N because you have no random access for list iterators. You can only do one step at a time with list iterators (these are bidirectional iterators).

    You can use boost::next and boost::prior

    // Lookahead in list to see if next element is end
    if(boost::next(iterItems) == dilList.end())  
    {
    

    Or you can print the comma before:

    std::string Compose(DataItemList& dilList)
    {
        std::stringstream ssDataSegment;
        for(iterItems = dilList.begin();
            iterItems != dilList.end(); 
            ++iterItems)
        {
            if(iterItems != diList.begin())
                ssDataSegment << ",";
            ssDataSegment << (*iterItems)->ToString();
        }
        return ssDataSegment.str();
    }
    

提交回复
热议问题