开发者

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>开发者_StackOverflow中文版;::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


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.


Yes, the iterator concept is completely independent of the concept of a container.

The standard library has a set of stream iterators, for example. Anything that can be iterated over should be represented by iterators in C++, whether or not there is an underlying in-memory container.


Boost.Range is geared around this concept.

http://www.boost.org/doc/libs/release/libs/range/index.html


Sounds to me like you are treating a Paragraph object as a container of paragrahs. But wouldn't a Paragraph be part of a container of Paragraphs? and each Paragraph be a container of words (or a string, depending on your needs)? so you could use the std::string iterator in the Paragraph object, and a std container to hold the Paragraph?

You can still create a custom iterator to iterate over what ever you want, however you want, the answer to this question gives a good overview of how to structure your iterator class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜