From: Yitzhak Sapir (yitzhaks_at_[hidden])
Date: 2002-08-08 10:06:25


There are only 3 or 4 algorithms that receive an _n argument though many times I've wanted to do a copy using an n or bound some other algorithm for n elements. In the case of strings the problem is solved since I can look up the function in string's many function interface, but many other classes and range types do not provide me this freedom. So, my question is: Is there such a thing as a bounded_iterator (for lack of a different name)?

My idea of a bounded_iterator would have an interface similar to filter_iterator, except it gets a difference_type bound. It maintains count through ++, --, and += of how far you are from the bounds, and any point beyond the bounds is considered end.

This way doing:
        std::copy (make_bounded_iterator(str.begin(), str.end(), 5), make_bounded_iterator(str.end()), std::back_inserter(copy_of_str));
would be equivalent to
        strncpy (new, str, 5);

Is there such a thing? (If not, is there any interest in having such a thing?) I tried to look on the site but didn't seem to find something like this, although using counting_iterator in some algorithms might give a similar effect. Perhaps using counting iterator with a filter and std::less might do something like it?

Incidentally, while I'm having problems using filter iterator in VC6, I think perhaps interface wise, it would be able to do make_filter_iterator(end_iter) to construct an end iterator.

My idea of semantics are as follows:
iter = make_bounded_iterator(begin, begin + 7, 5)
would act as follows, if the following are executed in sequence:
++iter --> iter now points begin + 1
iter += 5 -> iter now seems to point at begin + 7, because iter was begin + 1 to begin with, and adding five would have moved iter to begin + 6. Since that would have been out of bounds, the internal iterator is made to point at begin + 5, but the initialized "end" pointer is visible in this case -- so iter returns begin + 7. (Alternatively, this can be defined to be an invalid operation as is the following:)
++iter; --> this is undefined. iter points at end, so you can't increment iter.
--iter -> assuming this was executed after iter += 5, iter now points at begin + 4, since the internal iterator was pointing at begin + 5 to begin with. The internal iterator was moved back to begin + 4, was found to be within the range again. Therefore the the internal iterator is now visible as the value of iter.