从单个元素创建迭代器 [英] Create an iterator from a single element

查看:36
本文介绍了从单个元素创建迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在迭代器前添加一个元素.具体来说,我想创建一个迭代器,它可以逐步遍历序列 [2, 3, 5, 7, 9, ...] 直到某个最大值.我能想到的最好的是

I would like to prepend an element to an iterator. Specifically, I would like to create an iterator that steps through the sequence [2, 3, 5, 7, 9, ...] up to some maximum. The best I've been able to come up with is

range_step_inclusive(2,2,1).chain(range_step_inclusive(3, max, 2))

但是第一个迭代器是一种将单个元素 2 作为迭代器的技巧.是否有更惯用的方法来创建单元素迭代器(或将元素添加到迭代器)?

But the first iterator is kind of a hack to get the single element 2 as an iterator. Is there a more idiomatic way of creating a single-element iterator (or of prepending an element to an iterator)?

推荐答案

这是 std::iter::once.

创建一个只产生一个元素一次的迭代器.

Creates an iterator that yields an element exactly once.

这通常用于将单个值调整为 chain 其他类型的迭代.也许您有一个几乎涵盖所有内容的迭代器,但您需要一个额外的特殊情况.也许你有一个可以处理迭代器的函数,但你只需要处理一个值.

This is commonly used to adapt a single value into a chain of other kinds of iteration. Maybe you have an iterator that covers almost everything, but you need an extra special case. Maybe you have a function which works on iterators, but you only need to process one value.

range_step_inclusive 早已不复存在,所以我们也使用包含范围语法 (..=):

range_step_inclusive is long gone, so let's also use the inclusive range syntax (..=):

iter::once(2).chain((3..=max).step_by(2))

这篇关于从单个元素创建迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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