C ++ class with an iterator but no container

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

A simplified example of this might be, for example, a <Paragraph>::iteratorin a class that actually does not have a container with paragraphs, but instead has a variable <string> text. It's easy to create a member function that actually goes through a line by line and collect paragraphs, but it seems foolish to keep all this text again in some container so that I can inherit from iterators.

Also, the reason I named it <Paragraph>::iterator, unlike <string>::iterator, is because I might want to have a different type of iterator. For example, I could count the number of characters in each paragraph and have <int>::iterator.

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

thank

+3
source share
4 answers

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

Not only a suitable, but also a better way of thinking: classes should have common interfaces, that is, they should disclose only what they need to disclose, nothing more. How you process paragraphs domestically (whether you store them in a container, and if so, in which container) is an implementation detail and is not part of the class interface.

A class should in any case only display a range of paragraph iterators. And as soon as you, therefore, get rid of the container at the interface level, there may be no reason to have it inside the class, as you noticed yourself.

+6

, .

, , . , , ++, , .

+4

, Paragraph . Paragraph Paragraph s? Paragraph ( , )? std::string Paragraph std Paragraph?

You can still create your own iterator to iterate over whatever you want, but you want, the answer to this question gives a good overview of how to structure your iterator class.

0
source

All Articles