Search code examples
rustiterator

How to get distance between two iterators: C++ equivalent of std::distance


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
    }
}

Solution

  • 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 0
        }
    }
    

    playground