如何迭代C++中的抽象集合?
我有一个接口。该界面包含一种方法,该方法必须以某种方式让用户通过集合迭代。通常,我使用向量作为集合,因此我可以编写这样的代码:(
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返回了向量的一对开始和结束迭代器)
但是在这种情况下,我要做实现此接口的类,将向量用于存储对象,但有时可能会效率低下,因此我想使用list
例如,因为vector
会减慢我的程序。我也不想返回该集合,只想让用户迭代它。
因此,是否有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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用用于容器的模板参数,而不是容器内容:
当然,当使用
ITERATORS
时,您需要指定容器:您当然可以制作
接口
也可以使用模板。 ,如果在实现接口的混凝土类之前还不知道容器类型。但这使得与抽象接口
的指针一起使用多态性更难。Use the template argument for the container instead of the containers content:
Of course you then need to specify the container when using
Iterators
: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 abstractInterface
.