【问题标题】:custom iterator for a collection interface集合接口的自定义迭代器
【发布时间】:2015-08-11 14:13:54
【问题描述】:

我有一个接口 ICollection 实现了一个集合 ArdalanCollection,如下所示:

template <typename T>
class ICollection
{
public:
    virtual void add(T*) = 0;
    virtual T* get(int) = 0;
    virtual int count() = 0;
};

template <typename T>
class ArdalanCollection :public ICollection<T>
{
public:
    ArdalanCollection() {
        index = 0;
    };
    virtual void add(T* obj) {
        encapsolateImplementation.insert(make_pair(index++, obj));
    };
    virtual T* get(int index) {
        return encapsolateImplementation[index];
    };
    virtual int count() {
        return encapsolateImplementation.size();
    };
private:
    int index;
    unordered_map < int, T* > encapsolateImplementation;
};

我想要的是在 ICollection 接口中有一个通用迭代器,它可以循环所有内部容器元素(我还没有决定选择 unordered_map 作为我的内部容器,我可能会将其更改为 boost或者是其他东西)。我想以这种方式使用它:

    Node *node1 = new Node(1, 0, 0, 0);
    Node *node2 = new Node(1, 0, 0, 0);
    ICollection<Node> *nodes = new ArdalanCollection<Node>();
    nodes->add(node1);
    nodes->add(node2);
    for (it=nodes->iterator.begin(); it < nodes->iterator.end(); it++) {

    }

【问题讨论】:

标签: c++ interface iterator generic-programming


【解决方案1】:

首先,您的 for 循环习语不正确。它应该看起来像

for(auto it = nodes->begin(); it != nodes->end(); it++)

然后是:

template <typename T, typename MyMap>
class ICollection
{
public:
    typedef typename MyMap<int, T *>::iterator iterator;
    virtual void add(T*) = 0;
    virtual T* get(int) = 0;
    virtual int count() = 0;
};

应该没问题。

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 2018-09-06
    • 2013-02-17
    • 2015-02-04
    • 1970-01-01
    • 2016-06-18
    • 2013-01-12
    相关资源
    最近更新 更多