Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can STL algorithms be used with circular lists?

Tags:

c++

algorithm

stl

Creating an STL compliant iterator for your custom list is pretty mundane.

Yet, if the reffered list is a circular one, it seems quite pointless since all STL algorithms are operating on a [first, last) range and in a circular list first = last.

Is there a standard/consice way to overcome this obstacle and have STL algorithms operate on "home made" circular lists ?

I'm supposing defining STL compliant iterators is the first step to this goal, but a solution that would operate on ranges might also be possible.


I need to implement this for a plethora of "home made" structs. My current solution is to derive from boost::iterator_facade and then create a custom range class (like Rudolph's) and use any algorithm wrapped around range-based execution. Still this has some logical obstacles and would like to see alternatives and or solutions that worked out.

like image 910
Nikos Athanasiou Avatar asked Jun 02 '14 10:06

Nikos Athanasiou


People also ask

What is circular linked list How do you traverse a circular linked list?

The circular linked list is a linked list where all nodes are connected to form a circle. In a circular linked list, the first node and the last node are connected to each other which forms a circle. There is no NULL at the end.

How many algorithms are there in STL?

The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functions, and iterators.

How do you find the head in a circular linked list?

Follow the given steps to solve the problem: Declare a Node pointer node and initialize it to the head's next. Move node pointer to the next node, while the node is not equal to nullptr and node is not equal to the head. After coming out of the loop, check if the node is equal to head then return true, else return ...


1 Answers

You will need custom iterators, but the solution can still be range-based. One possibility is that begin() could return a specially marked iterator (flag initial=true) so that it knows that it hasn't made the round yet. end() would return an iterator with that flag set to false. Then operator++ would set the flag to false, so that begin() won't be equal to end(). You could use a different marking scheme as well.

like image 138
isarandi Avatar answered Sep 30 '22 04:09

isarandi