std::list iterator: get next element

前端 未结 6 1756
情书的邮戳
情书的邮戳 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:35

    You could avoid this problem altogether by using:

    std::string Compose(DataItemList& dilList)
    {
        std::stringstream ssDataSegment;
        for(iterItems = dilList.begin(); iterItems != dilList.end(); iterItems++)
        {
            ssDataSegment << (*iterItems)->ToString() << ","; // always write ","
        }
        std::string result = ssDataSegment.str();
        return result.substr(0, result.length()-1); // skip the last ","
    }
    

    You first write the "," for all elements (even for the last one). Than afterwards, you remove the unwanted last "," using substr. This additionally results in clearer code.

提交回复
热议问题