简体   繁体   English

迭代 [false, true] 的最有效方法是什么?

[英]What is the most efficient way to iterate in [false, true]?

I have a function foo that takes 3 booleans, and I would want to get the result of this function with every combination of bools.我有一个 function foo需要 3 个布尔值,我想得到这个 function 和布尔值的组合的结果。

Here is how I did it:我是这样做的:

fn foo(b1: bool, b2: bool, b3: bool) -> bool {
    b1 && b2 || !b3
}

fn main() {
    for b1 in vec![false, true] {
        for b2 in vec![false, true] {
            for b3 in vec![false, true] {
                println!("{} {} {} -> {}", b1, b2, b3, foo(b1, b2, b3));
            }
        }
    }
}

Is there a more direct/ shorter way to do it than creating a vector and then iterate through it?有没有比创建一个向量然后迭代它更直接/更短的方法?

Is there a way to do it with macros or with mutable functions, so that the compiler just go through each case without iterating?有没有办法使用宏或可变函数来做到这一点,以便编译器只需 go 通过每个案例而不进行迭代?

You could use the itertools crate and then use the iproduct!() macro.您可以使用itertools crate,然后使用iproduct!()宏。

use itertools::iproduct;

fn main() {
    const FT: &[bool; 2] = &[false, true];

    for (&b1, &b2, &b3) in iproduct!(FT, FT, FT) {
        println!("{} {} {} -> {}", b1, b2, b3, foo(b1, b2, b3));
    }
}

Not saying it's "more efficient", but it is shorter to write.不是说它“更高效”,而是写起来更短。

At the very least you can use arrays instead of vectors and thus save the dynamic allocations:至少您可以使用 arrays 代替向量,从而节省动态分配:

fn foo(b1: bool, b2: bool, b3: bool) -> bool {
  b1 && b2 || !b3
}

fn main() {
  for b1 in &[false, true] {
    for b2 in &[false, true] {
      for b3 in &[false, true] {
        println!("{} {} {} -> {}", 
                 b1, b2, b3,
                 foo(*b1, *b2, *b3));
      }
    }
  }
}

Then you can save on loop nesting by using itertools::iproduct!然后,您可以使用itertools::iproduct! :

use itertools::iproduct; // 0.9.0

fn foo(b1: bool, b2: bool, b3: bool) -> bool {
  b1 && b2 || !b3
}

fn main() {
  for (&b1, &b2, &b3) in iproduct!(&[false, true], &[false, true], &[false, true]) {
    println!("{} {} {} -> {}", 
             b1, b2, b3,
             foo(b1, b2, b3));
  }
}

(playground) (操场)

Ideally you'd write for b1 in [false, true] , but that's not yet possible .理想情况下,您会for b1 in [false, true]写,但这还不可能

Even without it, you can do better than allocating and consuming a Vec - for example, you can iterate over an array slice:即使没有它,您也可以比分配和使用Vec做得更好 - 例如,您可以遍历数组切片:

for &b1 in &[false, true] {
    for &b2 in &[false, true] {
        for &b3 in &[false, true] {
            ...

Note that the pattern specifies a reference (which dereferences the matched value) because iterating over a slice of T doesn't produce actual T values, but &T references to values that reside in the slice.请注意,该模式指定了一个引用(它取消引用匹配的值),因为迭代T的切片不会产生实际的T值,但&T引用驻留在切片中的值。

To iterate directly over a fixed small number of values, you can use std::iter::once() and chain() :要直接迭代固定的少量值,可以使用std::iter::once()chain()

for b1 in std::iter::once(false).chain(std::iter::once(true)) {
    ...

The above can be made slightly shorter by (mis)using Option , which is also iterable:通过(错误)使用Option可以使上面的内容稍微缩短一点,它也是可迭代的:

for b1 in Some(false).into_iter().chain(Some(true)) {
    ...

There's no need to overcomplicate things.没有必要把事情复杂化。 You can just do:你可以这样做:

fn main() {
    for i in 0..=0b111 {
        let a = (i & 1) == 1;
        let b = (i >> 1 & 1) == 1;
        let c = (i >> 2 & 1) == 1;
        println!("{} {} {} -> {}", a, b, c, foo(a, b, c));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 `&amp;str` 添加到 `String` 的最有效方法是什么? - What is the most efficient way to prepend a `&str` to a `String`? 将元素插入已排序向量的最有效方法是什么? - What's the most efficient way to insert an element into a sorted vector? 在Rust中重用迭代器的最有效方法是什么? - What's the most efficient way to reuse an iterator in Rust? 克隆固定大小数组的最有效方法是什么? - What is the most efficient way to clone a fixed-sized array? 在给定数值范围的引用上使用迭代器的最有效方法是什么? - What is the most efficient way to have a iterator over the references of a given numeric range? 获取多个整数用户输入并将其存储在 Vec 中的最有效方法是什么<i32> ? - What is the most efficient way of taking a number of integer user inputs and storing it in a Vec<i32>? 在不立即将整个文件加载到 memory 的情况下,分块读取大文件的最有效方法是什么? - What is the most efficient way to read a large file in chunks without loading the entire file in memory at once? 保持字符串引用集合的最有效方法 - Most efficient way to keep collection of string references 什么是最有效的:对 ArrayBase 或 ArrayView 的引用? - What's the most efficient: a reference to an ArrayBase or an ArrayView? 迭代扁平化 2D Vec 列的更有效方法 - More efficient way to iterate through columns of flattened 2D Vec
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM