C ++为每个在自定义集合 [英] C++ for each in on custom collections

查看:124
本文介绍了C ++为每个在自定义集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以自介绍以来,我一直爱的每个在关键字迭代 STL集合。是一个非常非常大的语法糖的粉丝)。

So since it was introduced I have been loving the for each in keywords to iterate STL collections.(I'm a very very big fan of syntactic sugar).

我的问题是如何写一个可以使用这些关键字迭代的自定义集合?

My question is how can I write a custom collection that can be iterated using these keywords?

什么APi我需要暴露我的集合使用这些关键字迭代?

Essentially, what APi do I need to expose for my collections to be iterable using these keywords?

如果这听起来很钝,请道歉,但请不要使用使用提升,不写自己的集合等。追求知识,我的朋友。如果不可能,嘿,我可以处理这个。

I apologize if this sounds blunt, but please do not respond with "use boost", "don't write your own collections", or the like. Pursuit of knowledge, my friends. If it's not possible, hey, I can handle that.

我也非常喜欢不必在我的集合中注入STL迭代器。

I'd also very much so prefer not to have to inject an STL iterator into my collections.

提前感谢!

推荐答案

这里是一个很好的解释可迭代数据结构(基于范围的循环):

Here is a good explanation of iterable data structures (Range-Based loops):

为了使数据结构可迭代,它必须与现有STL迭代器类似。

In order to make a data structure iterable, it must work similarly to the existing STL iterators.


  1. 必须有开始和结束在该结构上操作的方法,
    作为成员或立场

  2. 迭代器本身必须支持运算符* 方法, operator!= 方法和运算符++ 方法,作为成员或作为独立函数

  1. There must be begin and end methods that operate on that structure, either as members or as stand-alone functions, and that return iterators to the beginning and end of the structure.
  2. The iterator itself must support an operator* method, an operator != method, and an operator++ method, either as members or as stand-alone functions.

请注意,在 C ++ 11 对于基于范围的循环,不使用 STL ,虽然上述条件也适用于此。您可以在上面的相同链接阅读。

Note, in C++11 there is an integrated support for range-based loops without the use of STL, though the above conditions hold for this as well. You can read about it at the same link above.

这篇关于C ++为每个在自定义集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆