+ 1

What is need of using iterator type for custom iterators

Hi I tried creating a custom class with iterator. https://code.sololearn.com/c52WvnTAR09H If I am having below two lines or not, it does not matter in output: using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; Why all the articles suggests to have these two defined for iterator class?

28th May 2022, 7:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Answers
+ 1
This is what I found, These iterator tags are used for STL algorithms. Tags are used to select the most efficient algorithm if our container is passed to one of the Standard Library functions from the <algorithm> library. https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp#:~:text=also%20value_type%26%0A%7D%3B-,Why%20are%20tags%20useful,-%3F
28th May 2022, 8:45 AM
Vinit Sonawane
Vinit Sonawane - avatar
+ 1
Think of it as a supplement rather than requirement, of course algorithms will work without the tags. All algorithms will have a general implementation which is independent of the iterator tag. But some of those algorithms have multiple other EFFICIENT implementations based on the iterator_category tag. So if no tag is provided, a general implementation will be performed (no errors), and no default value for the tag is assumed. And how it works is the algorithm searches for typedef'd(or defined using 'using') "iterator_category" in the supplied iterator class definition, then if efficient implementation is available for that category, it performs that implementation instead of general implementation, and if not then performs general implementation. So it needs to specifically have "iterator_category" name and not any name.
28th May 2022, 3:40 PM
Vinit Sonawane
Vinit Sonawane - avatar
0
Thanks Vinit Sonawane ... I just tried using fill algorithm and it does not throw any error even though i have not provided tags. Is any tag by default assumed or what ? Also i am confused as how mapping happens ? Statement is like using and that name is any name we can choose... do we need to have specific name for tag ?
28th May 2022, 1:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta Thanks to you, I am learning new concepts.
28th May 2022, 3:40 PM
Vinit Sonawane
Vinit Sonawane - avatar