'How to iterate over an abstract collection in C++?
I have an interface. The interface contains a method that somehow must let a user iterate through a collection. Usually, I use a vector as the collection, so I could write the code like this:
class Object;
template<typename T>
using VectorIterators = std::pair<typename std::vector<T>::iterator, typename std::vector<T>::iterator>;
class Interface {
public:
virtual VectorIterators<Object> ListObjects() = 0;
};
(ListObjects returns a pair of begin and end iterators of the vector)
But in this case, I make classes that implement this interface use vector for storing objects, but sometimes it may be inefficient so I would want to use a list for example, since vector would slow my program down. I also don't want to return the collection, just want to let the user iterate through it.
So is there a way in C++ to iterate through an abstract collection that may store data in memory in any way? Do you have any ideas on how to solve it? Hope for your help!
Solution 1:[1]
Use the template argument for the container instead of the containers content:
template<typename T>
using Iterators = std::pair<typename T::iterator, typename T::iterator>;
Of course you then need to specify the container when using Iterators:
class Interface {
public:
virtual Iterators<std::vector<Object>> ListObjects() = 0;
};
You can of course make Interface a template as well, if the container type isn't known until the concrete classes which implements the interface. But that makes it harder to use polymorphism with pointers to the abstract Interface.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Some programmer dude |
