Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ class with an iterator but no container

I'm trying to implement a class that would allow me to iterate over objects STL-style without explicitly storing them in a container.

A simplified example of this would be, say, a <Paragraph>::iterator in a class that doesn't actually have a container of Paragraphs, but instead has a <string> text variable. It's easy to create a member function that actually goes through text line by line and assemble paragraphs but it seems silly to me to store all this text again in some container just so that I could inherit from it's iterators.

Also, the reason I called it a <Paragraph>::iterator as opposed to a <string>::iterator is because I may want to have an iterator of some different type. For example, I could count the number of chars in each of the paragraphs and have an <int>::iterator.

I guess my question is this: is it appropriate to think in terms of iterators when there's no container?

Thanks

like image 831
confusedCoder Avatar asked Dec 22 '22 12:12

confusedCoder


1 Answers

is it appropriate to think in terms of iterators when there's no container?

It’s not only appropriate, it’s the superior way of thinking: classes should have lean interfaces – that is, they should only expose what they need to expose, nothing more. How you handle paragraphs internally (whether you store them in a container, and if so, in which container) is an implementation detail and doesn’t belong in the class’ interface.

The class should in any case only expose an iterator range of the paragraphs. And once you’ve thus got rid of the container on the interface level there might not be a reason to have one inside the class, as you’ve noticed yourself.

like image 126
Konrad Rudolph Avatar answered Jan 17 '23 02:01

Konrad Rudolph