zoukankan      html  css  js  c++  java
  • rust 迭代器

    https://blog.csdn.net/guiqulaxi920/article/details/78823541

    fn main() {
    
        // Basic Range (exclusive on the right)
        for i in 1..11 {
            print!("{} ", i);
        }
        println!("");
    
        // Inclusive range
        for i in 1..=10 {
            print!("{} ", i);
        }
        println!("");
    
        // use of discard "_" pattern
        let mut n: i32 = 0;
        for _ in 0..10 {
            n += 1;
        }
        println!("num = {}", n);
    
        // count()
        println!("num = {}", (0..10).count());
    
        // Range with step using a filter
        for i in (0..21).filter(|x| (x % 2 == 0)) {
          print!("{} ", i);
        }
        println!("");
    
    
        // Reverse range
        for i in (0..11).rev() {
            print!("{} ", i);
        }
        println!("");
    
        // map()
        for i in (1..11).map(|x| x * x) {
            print!("{} ", i);
        }
        println!("");
    
        // fold()
        let result = (1..=5).fold(0, |acc, x| acc + x * x);
        println!("result = {}", result);
    }
    [root@bogon iter]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    num = 10
    num = 10
    0 2 4 6 8 10 12 14 16 18 20 
    10 9 8 7 6 5 4 3 2 1 0 
    1 4 9 16 25 36 49 64 81 100 
    result = 55
    #![feature(inclusive_range_syntax)]
    
    let mut acc = 0;
    
    for x in 1...5 {
      acc += x * x;
    }
    
    let result = acc;
    println!("result = {}", result);
    
    // output: result = 55
  • 相关阅读:
    一点优化小知识
    网站结构优化之一
    [JOISC 2016 Day 3] 电报
    [HDU 6157] The Karting
    [JOISC 2015 Day2] Keys
    Educational Codeforces Round 107 (Rated for Div. 2)
    [JOISC 2020 Day4] 治疗计划
    CF1131G Most Dangerous Shark
    [APIO2016] 划艇
    [ICPC World Finals 2018] 绿宝石之岛
  • 原文地址:https://www.cnblogs.com/dream397/p/14202732.html
Copyright © 2011-2022 走看看