Why pop_if do not receive equal?

#![feature(vec_pop_if)]


#[derive(Debug)]
struct A {
    pub dd: i32,
}
fn main() {
    let mut c = vec![A { dd: 1 }, A { dd: 2 }, A { dd: 3 }, A { dd: 4 }];

    if let Some(mut order) = c.pop_if(|x| x.dd == 3) {
        println!("ff: {:?}", order);
    }
    
       if let Some(mut order) = c.pop_if(|x| x.dd >= 3) {
        println!("cc: {:?}", order);
    }
}
// only got this 
cc: A { dd: 4 }

see here Rust Playground

Vec::pop_if pops the last element of the vector if the predicate is true, not the last element where the predicate is true. Your last element is A { dd: 4 }, it does not match |x| x.dd == 3, so it is not popped.

2 Likes

Maybe you meant...

    if let Some(idx) = c.iter().position(|x| x.dd == 3) {
        let order = c.remove(idx);
        println!("ff: {:?}", order);
    }

...or...

    if c.iter().find(|x| x.dd == 3).is_some() {
        let order = c.pop().unwrap();
        println!("ff: {:?}", order);
    }

...or something else (it's not clear exactly what you expected).

2 Likes

yeah , I misunderstood the description of this API.

"pop" always means removing the last (or first, depending on the data structure) element, and it implies O(small), and "the most easily accessible element" – it's a ubiquitous term in computing.

Nobody uses "pop" for "remove an arbitrary element in linear time".

1 Like

Got it. Thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.