rust - How to get distance between two iterators: C++ equivalent of std::distance - Stack Overflow

admin2025-04-17  3

I'm trying to get the distance between two iterators(C++ equivalent of std::distance). But with the below code logic I'm not able to.

fn main() {
    let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];
    for x in list.iter().skip(3).take(100) {
        print!("{}, ", x);
    }
    println!();
    
    let itr1 = list.iter().enumerate().next();
    let itr2 = list.iter().skip(5).enumerate().next();
    
    if itr1.is_some() && itr2.is_some() {
        println!("{}: {}", itr1.unwrap().0, itr1.unwrap().1);
        println!("{}: {}", itr2.unwrap().0, itr2.unwrap().1);
        
        let d = itr2.unwrap().0 - itr1.unwrap().0;
        println!("{}", d); // prints 0
    }
}

I'm trying to get the distance between two iterators(C++ equivalent of std::distance). But with the below code logic I'm not able to.

fn main() {
    let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];
    for x in list.iter().skip(3).take(100) {
        print!("{}, ", x);
    }
    println!();
    
    let itr1 = list.iter().enumerate().next();
    let itr2 = list.iter().skip(5).enumerate().next();
    
    if itr1.is_some() && itr2.is_some() {
        println!("{}: {}", itr1.unwrap().0, itr1.unwrap().1);
        println!("{}: {}", itr2.unwrap().0, itr2.unwrap().1);
        
        let d = itr2.unwrap().0 - itr1.unwrap().0;
        println!("{}", d); // prints 0
    }
}
Share Improve this question asked Feb 1 at 4:53 HarryHarry 3,2581 gold badge24 silver badges46 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Right now you have each iterator counting from its start point. Simply arrange for them to count from the same point by calling enumerate before you start moving (e.g. with skip):

fn main() {
    let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];
    for x in list.iter().skip(3).take(100) {
        print!("{}, ", x);
    }
    println!();
    
    let itr1 = list.iter().enumerate().next();
    let itr2 = list.iter().enumerate().skip(5).next();    // <-- change this line
    
    if itr1.is_some() && itr2.is_some() {
        println!("{}: {}", itr1.unwrap().0, itr1.unwrap().1);
        println!("{}: {}", itr2.unwrap().0, itr2.unwrap().1);
        
        let d = itr2.unwrap().0 - itr1.unwrap().0;
        println!("{}", d); // prints 5
    }
}

playground

转载请注明原文地址:http://anycun.com/QandA/1744838997a88335.html