[英]How do I add foreach iteration support to my own collection class in C++?
I have created a C++ implementation of a collection type.我创建了一个集合类型的 C++ 实现。 I would like to add iteration support so that developers may use the "for each" statement on it.
我想添加迭代支持,以便开发人员可以在其上使用“for each”语句。 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:标准习惯用法是:公开类型
iterator
和const_iterator
并提供最少两个函数,即begin()
和end()
为:
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>
.一旦你实现了这些,你的集合就可以在
std::for_each
中使用,以及在<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.假设您的意思是
for_each
算法,您只需要代表标准begin
和end
容器方法的东西:指向逻辑容器中第一个和一个过去端点的迭代器。
If you mean the STL's for_each
algorithm, you just need to define begin()
and end()
like the STL containers do.如果你指的是 STL 的
for_each
算法,你只需要像 STL 容器那样定义begin()
和end()
。
If you mean C++0x's range-based for loop, then you can just do the same thing.如果你的意思是 C++0x 的基于范围的 for 循环,那么你可以做同样的事情。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.