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?
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.
The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element.
If iter is an InputIterator, you can use: ++iter and iter++ to increment it, i.e., advance the pointer to the next element.
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.
Note: Since C++11 you can use std::next and std::prev.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With