• collections


    Storing Lists of Values with Vectors

    Vector

    The first collection type we'll look at is Vec<T>, as known as a Vector. Vector allows you to store more than one value in a single data structure that puts all the values next to each other in memory.

    How to use a vector

    Let me explain the usage with a simple but classic instance:

    //vector
    fn ve() {
        //create a new instance
        let v: Vec<i32> = Vec::new();
        //it's mote common to create a vector that has initial values
        //as the compiler can infer the type i32 from the initial values, 
        //so we don't need the Vec<i32> annotation.
        let mut v = vec![1,2,3];
        
        //push in some values
        v.push(4);
        v.push(5);
    
        //two ways to access elements in a vector with index
        let third = &v[2];
        match v.get(3) {
            Some(third) => println!("vector third element is {}", third),
            None => println!("there is no third element"),
        }
        /*
         * differences between [] and get
         * []: give us a i32 type element or &i32 type if we use &
         * get: give us a Option<&T> type element
         */
        
        //what if we access an element with an unexisted index
        //let sixth = &v[5]; //panic when run the program
        let six = v.get(5); //return None
    
        /*
         * iterating over the values in a vector with the for loop
         */
        for i in &v {
            println!("{}", i);
        }
        //use mutable reference
        for i in &mut v {
            *i += 1;//we have to use the dereference operator(*) to get to the value in i before we can use the += operator
        }
    
        //pop: removes the last element from a vector and returns it
        println!("last element of the vector: {}", v.pop().unwrap());//unwrap is a Option<T> function to get the T value.
    
        //drain: creates a draining iterator that removes the specified range in the vector and yields the removed items.
        let dr: Vec<_> = v.drain(1..).collect();//collect is a function of iterator, we'll cover it later.
        assert_eq!(v.len(), 1);
    }
    

    Little details:

  • 相关阅读:
    现代软件工程 第八章 【需求分析】练习与讨论
    现代软件工程 第七章 【MSF】练习与讨论
    现代软件工程 第六章 【敏捷流程】练习与讨论
    PPT演说技巧
    Mac上最强大的截图软件-xnip
    什么是函数倾轧(name mangling)?
    编程--在线提交系统(Online Judge)
    C++ 的多继承与虚继承
    C++ 中 string和char* 的区别
    编程语言中优先级与结合性
  • 原文地址:https://www.cnblogs.com/lunar-ubuntu/p/14328725.html
Copyright © 2020-2023  润新知