How to compare vec and return a bool array

code first as below: (of course it cannot be complied)

fn main(){
    let a = vec![10,20,30];
    let b:Vec<Bool> = a>15;     //I want a result like: vec![false, true, true]
    println!("{:?}", b);

}

background:
I'd like to have a vec, and compare with another number, then directly get a bool array.
I know the std::ops::Add, it's easy to impl it to other places,
whether rust std libary provide such implementation for the comparison(equal =, bigger >, smaller <) ?

You can do this with iterators.

fn main() {
    let a = vec![10, 20, 30];
    let b: Vec<bool> = a.iter().map(|&val| val > 15).collect();
    println!("{:?}", b);
}
[false, true, true]

appreciate for your help,
for this code, let b: Vec = a.iter().map(|&val| val > 15).collect();
it works well,
I just want to have this long sentence to be hidden and directly input such as : a>15 (a is a vec arrary), then directly get the result,
the reason why I need this because I need to put it as a condition arrary in another function,

so I want to impl the comparsison background and directly output the final bool arrary.

Rust doesn't have anything like this built-in, and it's not possible to add this feature, at least not for the built-in Vec type. If you want to shorten the expression, perhaps a helper function could help?

fn broadcast_gt(arr: &[i32], val: i32) -> Vec<bool> {
    arr.iter().map(|a| *a > val).collect()
}
1 Like

it's great, thanks so much..

It looks like you are looking for an array/tensor library – for that, there is ndarray.

2 Likes