当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - custom iterator for a collection interface

问题描述:

I have an interface ICollection implementing a collection ArdalanCollection like this:

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;

};

what I want is to have a generic iterator in ICollection interface which can loop all over the internal container elements(I haven't decided to choose unordered_map as my internal container I might change it to boost or something else). I want to use it in this way:

 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++) {

}

网友答案:

First your for loop idiom is not correct. It should rather look like

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

then something along:

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;
};

should be fine.

分享给朋友:
您可能感兴趣的文章:
随机阅读: