如何在包含枚举索引的2D数组上返回迭代器? [英] How do I return an iterator over a 2D array with the enumeration indices included?

查看:55
本文介绍了如何在包含枚举索引的2D数组上返回迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2D数组的结构:

I have a struct containing a 2D array:

struct Block;

struct World {
    blocks: [[Block; 10]; 10],
}

我如何编写一个在2D数组上返回迭代器但包含枚举索引的函数?

How could I write a function which returns an iterator over a 2D array, but with the enumeration indices included?

fn enumerate_blocks(&self) -> impl Iterator<Item = (usize, usize, &Block)>

我设法编写了一个函数的实现,该函数只返回没有枚举索引的迭代器:

I managed to write an implementation of the function which just returns an iterator without enumeration indices:

fn blocks(&self) -> impl Iterator<Item = &Block> {
    self.blocks.iter().flat_map(|x| x.iter())
}

如果我致电 Iterator::enumerate 一次,我将在(usize, [B; 10])上得到一个迭代器.接下来我该怎么做才能在(usize, usize, B)上获得迭代器?

If I call Iterator::enumerate once, I will get an iterator over (usize, [B; 10])s. What I can do next to get an iterator over (usize, usize, B)s?

我知道我可以使函数返回自定义结构,然后像image一样实现Iterator,但理想情况下,我希望避免这种情况.

I know I could make the function return a custom struct then implement Iterator, like image does, but ideally I would like to avoid this.

推荐答案

如果我一次调用Iterator::enumerate,我将在(usize, [B; 10])上获得一个迭代器.接下来我该怎么做才能在(usize, usize, B) s上获得迭代器?

If I call Iterator::enumerate once, I will get an iterator over (usize, [B; 10])s. What I can do next to get an iterator over (usize, usize, B)s?

致电 Iterator::enumerate 内部数组,以相同的方式继续使用 Iterator::flat_map 进行组合.使用 Iterator::map 添加外部索引到内部元组.

Call Iterator::enumerate on the inner array in the same way, continuing to use Iterator::flat_map to combine them. Use Iterator::map to add the outer index to the inner tuple.

#[derive(Debug, Default)]
struct Block;

#[derive(Debug, Default)]
struct World {
    blocks: [[Block; 2]; 3],
}

impl World {
    fn blocks(&self) -> impl Iterator<Item = (usize, usize, &Block)> {
        self.blocks
            .iter()
            .enumerate()
            .flat_map(|(x, v)| v.iter().enumerate().map(move |(y, v)| (x, y, v)))
    }
}

fn main() {
    let w = World::default();
    for (x, y, v) in w.blocks() {
        println!("{}, {}, {:?}", x, y, v)
    }
}

0, 0, Block
0, 1, Block
1, 0, Block
1, 1, Block
2, 0, Block
2, 1, Block

这篇关于如何在包含枚举索引的2D数组上返回迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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