最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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
    }
}

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,1501 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

发布评论

评论列表(0)

  1. 暂无评论