Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I define begin and end on an input iterator?

Lets say I have an input iterator type MyInputIter (which I use to traverse a tree-like structure) that satisfies the std::input_iterator concept.

Are there any reasons why I shouldn’t define begin() and end() on the iterator itself?

struct MyInputIter
{
    // iterator stuff omitted

    auto begin() const { return *this; }
    auto end() const { return MySentinel{}; }
};

Reason being that I don’t have to create another type just to wrap begin and end so I can use it in a for loop:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MyInputIter iterate(TreeNode root, FilterPattern pattern)
{
    return MyInputIter{ root, pattern };
}

void foo()
{
    for (auto item : iterate(someRandomTreeNode, "*/*.bla"))
        process(item);
}

while also being able to use it as an iterator:

std::vector<TreeNode> vec(iterate(someRandomTreeNode, "*"), MySentinel{});

>Solution :

Are there any reasons why I shouldn’t define begin() and end() on the iterator itself?

Potential issues to consider:

  1. Implementing those functions for the iterator may be expensive. Either because of need to traverse the structure to find them, or because of extra state stored in the iterator.
  2. It may be confusing since it deviates from common patterns. Edit: As pointed out by 康桓瑋, there’s precedent for iterators that are ranges in std::filesystem::directory_iterator, so this may not a significant issue.

Reason being that I don’t have to create another type

As far as I can tell, you don’t need to create another type. You can use:

std::ranges::subrange(MyInputIter{ root, pattern }, MySentinel{})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading