简体   繁体   English

通用迭代器

[英]Generic iterator

I am trying to find a generic way of accessing a set of containers. 我试图找到一种访问一组容器的通用方法。 I have a standard vector and list in addition to another custom list. 除了另一个自定义列表外,我还有一个标准的矢量和列表。

The custom list defines an iterator; 自定义列表定义了一个迭代器;

class Iterator: public std::iterator<std::forward_iterator_tag, T> {
    // ...
}

Iterator begin() {
    return (Iterator(root));
}

Iterator end() {
    return (Iterator(NULL));
}

with the appropriate operators overloaded. 与适当的运算符重载。

Ideally, I would like to do this; 理想情况下,我想这样做;

class Foo {
public:
    Foo() {
        std::list<int> x;
        std::vector<int> y;
        custom_list<int> z;

        iter = x.begin(); // OR
        iter = y.begin(); // OR
        iter = z.begin();

        // ...
    };
private:
    std::iterator<int> iter;
};

But obviously these are all iterators of different types. 但显然这些都是不同类型的迭代器。 I can assume all the containers are of the same type however. 我可以假设所有容器都是相同类型的。

Is there an elegant way to solve this problem? 有没有一种优雅的方法来解决这个问题?

Better late than never... 迟到总比不到好...

The latest issue of C-Vu turned up and guess what was in it: That's right, iterators that do exactly what you wanted. 最新一期的C-Vu出现并猜测其中的内容:这是正确的,迭代器完全符合您的要求。

Unfortunately you need to become a member of the ACCU to view the magazine (the article references the Overload article from 2000 that David links to). 不幸的是,您需要成为ACCU的成员才能查看该杂志(该文章引用了David链接到2000年的Overload文章)。 But for a measly price a year you get a nice magazine to read, conferences and user groups. 但是,对于每年一个不起眼的价格,你会得到一本很好的杂志阅读,会议和用户群。 When you become a member you can view PDF's of the back issues so what are you waiting for ? 当您成为会员时,您可以查看PDF背面问题,那么还等什么呢?

A case of being careful what you ask for. 一个小心你要求的案例。 The any_iterator classes you see work on an unbounded set of iterator types. 您看到的any_iterator类可以处理一组无限的迭代器类型。 You only have three, which you know up front. 你只有三个,你事先知道。 Sure, you might need to add a fourth type in the future, but so what if that takes O(1) extra lines of code ? 当然,您可能需要在将来添加第四种类型,但是如果需要额外的O(1)代码行呢?

The big advantage of a closed set of possible contained types is that you have an upper bound on sizeof(), which means you can avoid the heap and the indirection it brings. 封闭的一组可能包含的类型的一大优点是你有一个sizeof()的上限,这意味着你可以避免堆和它带来的间接。 Basically, stuff them all in a boost::variant and call apply_visitor. 基本上,将它们全部填入boost :: variant并调用apply_visitor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM