JohanS said:
Hi
I have created my own linked list where last always points to first so
the list is like a circle that goes round and round.
Now i wanna use the list from the STL instead but i still want the
last element to point to the first. Is there some good way of doing
this with the STL list?
You could write a wrapper around a std::list::iterator so that incrementing
an iterator wrapper that was at the end of the std::list would cause it to
return to the first element, and decrementing an iterator wrapper that was
at the beginning of the std::list would cause it to jump to the last
element. Simple example:
template <class ListType>
class CircularIterator {
ListType& list;
typename ListType::iterator it;
public:
CircularIterator(ListType& theList) : list(theList), it(list.begin()){}
CircularIterator& operator++() {
// do nothing on empty list
if ( it != list.end() ) {
++it;
if ( it == list.end() ) {
it = list.begin();
}
}
return *this;
}
CircularIterator& operator--() {
// do nothing on empty list
if ( it != list.end() ) {
if ( it == list.begin() ) {
it = list.end();
}
--it;
}
return *this;
}
typename ListType::reference operator*() {
return *it;
}
typename ListType::iterator operator->(){
return it;
}
};
typedef std::list<int> List;
typedef CircularIterator<List> Iter;
int main()
{
List list;
for ( int i = 0; i < 9; ++i ) {
list.push_back(i);
}
Iter it(list);
std::cout << "Forward" << std::endl;
do {
std::cout << *it << std::endl;
++it;
} while ( *it != 0 );
std::cout << "Reverse" << std::endl;
do {
std::cout << *it << std::endl;
--it;
} while ( *it != 0 );
return 0;
}