Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::list iterator: get next element

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 string should be "A,B,C,D".

This code does not work:

typedef std::list< shared_ptr<EventDataItem> > DataItemList;
// ...
std::string Compose(DataItemList& dilList)
{
    std::stringstream ssDataSegment;
    for(iterItems = dilList.begin();
        iterItems != dilList.end(); 
        iterItems++)
    {
        // Lookahead in list to see if next element is end
        if((iterItems + 1) == dilList.end())  
        {
            ssDataSegment << (*iterItems)->ToString();
        }
        else
        {
            ssDataSegment << (*iterItems)->ToString() << ",";
        }
    }
    return ssDataSegment.str();
}

How do I get at "the-next-item" in a std::list using an iterator? I would expect that it's a linked-list, why can't I get at the next item?

like image 810
J. Polfer Avatar asked Apr 23 '10 15:04

J. Polfer


People also ask

How do I access next iterator?

Advancing iterator in Lists: Since, lists support bidirectional iterators, which can be incremented only by using ++ and – – operator. So, if we want to advance the iterator by more than one position, then using std::next can be extremely useful.

How do I get the iterator to the last element in a list?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element.

How do you increment iterators?

If iter is an InputIterator, you can use: ++iter and iter++ to increment it, i.e., advance the pointer to the next element.

How do you find the next element of a vector?

In case you use the vector as a circular list (that is, you consider the first element as the "next" of the last element), you can use the modulo operator against the length of the vector. This solution is useful if you need to select the next element in a "round robin" way, especially out of a loop.


2 Answers

Note: Since C++11 you can use std::next and std::prev.

like image 131
user1823890 Avatar answered Oct 06 '22 00:10

user1823890


Yet another possibility:

#include "infix_iterator.h"
#include <sstream>

typedef std::list<shared_ptr<EventDataItem> > DataItemList;

std::string Compose(DataItemList const &diList) {
    std::ostringstream ret;
    infix_ostream_iterator out(ret, ",");

    for (item = diList.begin(); item != diList.end(); ++item)
        *out++ = (*item)->ToString();
    return ret.str();
}

You can get infix_iterator.h from Google's Usenet archive (or various web sites).

like image 44
Jerry Coffin Avatar answered Oct 05 '22 22:10

Jerry Coffin