Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle iterator::difference_type when you have no way of measuring the difference?

I'm writing a C++ wrapper for a 3rd party C library.

The library provides some functions for iterating through a series of objects.

I want to write an iterator to wrap this behaviour so iteration is easier, but I cannot think how I will be able to provide the mandatory 'difference' type since the iterated objects don't have a meaningful relative order and the API I am working with does not provide a means of finding the number of objects available in advance.

I can't count the objects as they're iterated because although that would solve individual iterators it would render the difference between the end() iterator and other iterators undefined.

like image 613
Pharap Avatar asked Oct 11 '17 18:10

Pharap


1 Answers

All iterators in C++ need to provide some sort of difference_type. Whether or not that type is meaningful or useful is a completely separate issue.

From what you're describing, it seems like you're working with an input iterator, which gives you the ability to make a single pass over a stream of data but not to back up or save positions in the stream. For input iterators, there's still a requirement to have a difference_type defined, but there's no meaningful way to take the difference of two iterators. The only way to measure distance is to manually count up how many elements you've seen as you go.

Using the default of std::ptrdiff_t is probably very reasonable here unless you have a data stream that can produce so many elements that you can't fit the number of them into a std::ptrdiff_t. Clients can then use this to count up how many things they've seen, even though your iterator doesn't actually let people compute distances between entries.

like image 196
templatetypedef Avatar answered Sep 20 '22 16:09

templatetypedef