开发者

How do I add foreach iteration support to my own collection class in C++?

I have created a C++ implementation of a collection type. I would开发者_如何学运维 like to add iteration support so that developers may use the "for each" statement on it. How can I do that?


The standard idiom is : expose types iterator and const_iterator and provide minimum two functions namely, begin() and end() as:

template</*.....*/>
class Collection
{
 public:
     typedef /*...*/ iterator;
     typedef /*...*/ const_iterator;

     iterator begin();
     iterator end();

     const_iterator begin() const;
     const_iterator end() const;
};

Once you implement these, your collection can be used in std::for_each, and in a lot other algorithmic functions which are defined in <algorithm>.


Assuming you mean the for_each algorithm, you just need something that represents the standard begin and end container methods: iterators to the first and one-past-end points in your logical container.


If you mean the STL's for_each algorithm, you just need to define begin() and end() like the STL containers do.

If you mean C++0x's range-based for loop, then you can just do the same thing.


using namespace std;

// very very simple container class
class Cont {
public:
    Cont() {}
    typedef char* iterator;
    iterator begin() {return arr;}
    iterator end() {return &arr[200];}

private:
    char arr[200];
};

void setit(char &it) {
    it = 'a';
} 
// iterator must provide ++ operation for for_each algorithm (char* in this example works this way)
int main() {
    Cont c;
    for_each(c.begin(), c.end(), setit);
    copy(c.begin(), c.end(), ostream_iterator<char>(cout, ","));
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜