【问题标题】:How can I push an iterator to an existing vector (or any other collection)?如何将迭代器推送到现有向量(或任何其他集合)?
【发布时间】:2015-08-12 22:15:50
【问题描述】:

查看文档或 Rust 0.12,我看到 the following method 将多个值推送到已经存在的 Vec

fn push_all(&mut self, other: &[T])

但是,如果我有一个迭代器,我认为使用它不是有效的:vector.push_all(it.collect().as_ref())。有没有更有效的方法?

【问题讨论】:

    标签: collections rust iterator


    【解决方案1】:

    您可以使用Vecextend methodextend 采用实现 IntoIterator(包括所有迭代器类型)的任何类型的值,并通过从迭代器返回的所有元素扩展 Vec

    vector.extend(it)
    

    由于extend 属于Extend 特征,它也适用于许多其他集合类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 2020-11-06
      • 1970-01-01
      • 2013-01-25
      • 2018-07-09
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多