HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How to count the elements in a vector with some value without looping?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withhowsomeloopingcountthewithoutvectorvalueelements

Problem

How do I count the elements in a vector (e.g. [91, 55, 77, 91]) with a certain value (e.g. 91) without using a loop (as shown below)?

fn count_eq(vec: &Vec, num: i64) -> i64 {
    let mut counter = 0;
    for i in vec {
        if *i == num {
            counter += 1;
        }
    }
    return counter;
}

fn main() {
    let v = vec![91, 55, 77, 91];
    println!("count 91: {}", count_eq(&v, 91));
}

Solution

You can use Iterator::filter and then count it:

fn main() {
    let v = vec![91, 55, 77, 91];
    println!("count 91: {}", v.iter().filter(|&n| *n == 91).count());
}

Code Snippets

fn main() {
    let v = vec![91, 55, 77, 91];
    println!("count 91: {}", v.iter().filter(|&n| *n == 91).count());
}

Context

Stack Overflow Q#45353757, score: 83

Revisions (0)

No revisions yet.