如何迭代C++中的抽象集合?

发布于 2025-01-31 19:30:00 字数 580 浏览 3 评论 0原文

我有一个接口。该界面包含一种方法,该方法必须以某种方式让用户通过集合迭代。通常,我使用向量作为集合,因此我可以编写这样的代码:(

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随波逐流 2025-02-07 19:30:00

使用用于容器的模板参数,而不是容器内容:

template<typename T>
using Iterators = std::pair<typename T::iterator, typename T::iterator>;

当然,当使用ITERATORS时,您需要指定容器:

class Interface {
public:
    virtual Iterators<std::vector<Object>> ListObjects() = 0;
};

您当然可以制作接口也可以使用模板。 ,如果在实现接口的混凝土类之前还不知道容器类型。但这使得与抽象接口的指针一起使用多态性更难。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文