vector in Rust

1
2
3
4
5
struct Vec {
  length: u32,            //Present size of vector
  ptr: RefCell,           //Pointer to allocate Memory on Heap
  capacity: u32,          //Max size vector can hold, after this vector need to be resized/reallocated
}

create

不指定数据类型

1
2
let mut v1 = Vec::new();  
let mut v2 = vec![];

指定数据类型

1
2
3
let mut v1:Vec<i32> = Vec::new();
let mut v2:Vec<i32> = vec![];
let mut v3 = vec![1i32, 2,3];

创建并初始化

1
2
3
4
5
6
let mut v1 = vec![1,2,3];
let mut v2:Vec<i32> = vec![1,2,3];
let mut v3 = vec![1i32,2,3];
let mut v4 = vec![1; 10];
let mut v5: Vec<i32> = (0..10).collect();
let v6: Vec <i32> = [1,2,3].to_vec();

2D vector

1
2
3
let mut 2d_vec: Vec<Vec<i32>> = Vec::new();
let mut 2d_vec: Vec<Vec<i32>> = 
vec![vec![0; row as usize]; col as usize];

convert from slic

1
2
3
4
5
fn main() {
    let a = &[1,2,3];
    let v1 = a.to_vec();
    println!("{:?}", v1)
}
1
2
3
4
5
fn main() {
    let a = &[1,2,3];
    let v1 = Vec::from(a);
    println!("{:?}", v1)
}
1
2
3
4
5
6
fn main() {
    let mut v1 = Vec::new();
    let a = &[1,2,3];
    v1.extend_from_slice(a);
    println!("{:?}", v1)
}

访问元素

read

1
2
3
4
let mut v1 = vec![1,2,3];
let item = v1[0];
println!("{:?},{:?}", v1.get(0),v1.get(100));
//Some(1),None

slice

1
2
3
let v1 = vec![1,2,3,4,5];
let v2 = v1[1..];
let v2 = v1[1..3];

write

1
2
let mut v1 = vec![1,2,3];
v1[0] = 11;

insert

1
2
3
4
5
6
fn main() {
    let mut v1 = vec![1,2,3];
    v1.insert(2,1);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 1, 3]

remove

1
2
3
4
let mut v1 = vec![1,2,3];
v1.remove(0);
println!("v1:{:?}",v1);
// v1:[2, 3]

clear

1
2
3
4
5
6
7
8
fn main() {
    let mut weapons = vec!["Andúril", "Sting", "Glamdring"];

    weapons.clear();

    println!("Weapons after the war: {:?}", weapons);
}

append

1
2
3
4
5
6
7
fn main() {
    let mut v1 = vec![1,2,3];
    let mut v2 = vec![4,5,6];
    v1.append(&mut v2);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 3, 4, 5, 6]

extend

1
2
3
4
5
6
let mut vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];

vec1.extend(vec2);

assert_eq!(vec1, [1, 2, 3, 4, 5, 6]);
1
2
3
4
5
6
7
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];

let mut vec3 = vec1;
vec3.extend(vec2.into_iter());

assert_eq!(vec3, [1, 2, 3, 4, 5, 6]);
1
2
3
4
5
6
7
8
9
fn main() {
    let mut army_of_men = vec!["Aragorn"];
    let elves_and_dwarves = vec!["Legolas", "Gimli"];

    // The Elves and Dwarves join the coalition
    army_of_men.extend(elves_and_dwarves);

    println!("United Army: {:?}", army_of_men);
}

sort

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fn main() {
    let mut v1 = vec![1,2,3, 3,2,1];

    v1.sort();

    println!("v1:{:?}",v1);
    let result = v1.binary_search(&2);

    println!("result:{:?}",result);
}
// v1:[1, 1, 2, 2, 3, 3]
// result:Ok(3)

resize

1
2
3
4
5
6
7
8
9
fn main() {
    let mut v1 = vec![1,2,3, 3,2,1];
    v1.resize(10, 0);
    println!("v1:{:?}",v1);
    v1.resize(2, 0);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 3, 3, 2, 1, 0, 0, 0, 0]
// v1:[1, 2]

push and pop

1
2
3
4
let mut v1 = vec![1,2,3];
v1.push(4);
v1.push(5);
let item = v1.pop();

iterator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let mut v = vec![1,2,3];

for item in &v {

}

for item in &mut v {

}

for item in v {

}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let mut v = vec![1,2,3];
for (i, x) in v.iter().enumerate() {
        println!("In position {} we have value {}", i, x);
}

for x in v.iter() {
       println!("item:{}",x);
}

for x in v.iter_mut() {
        *x *= 3;
}
println!("Updated vector: {:?}", xs);
1
2
3
let items = vec![1, 2, 3];
let sitems = items.into_iter().map(|x| x.to_string()).collect::<Vec<_>>();
println!("sitem: {:?}",sitems);

concat()

1
2
3
4
5
6
7
8
9
fn main() {
    let elves = vec!["Legolas", "Thranduil"];
    let dwarves = vec!["Gimli", "Thorin"];

    // Uniting Elves and Dwarves
    let united_army = [elves, dwarves].concat();

    println!("United army: {:?}", united_army);
}

属性

capacity

1
2
let mut v1 = vec![1,2,3];
println!("capacity={}",v1.capacity());

len

1
2
let mut v1 = vec![1,2,3];
println!("len={}",v1.len());

is_empty

1
2
let mut v1 = vec![1,2,3];
println!("is_empty={}",v1.is_empty());

contains

1
2
3
4
5
6
7
8
9
fn main() {
    let mut v1 = vec![1,2,3];

    println!("{} is in v1:{:?}",1, v1.contains(&1));

    println!("{} is in v1:{:?}",11, v1.contains(&11));
}
// 1 is in v1:true
// 11 is in v1:false

application

storing enum in vector

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use std::{string::String, u32};
#[derive(Debug)]
enum Address{
    NoIP,
    IPv4(u8,u8,u8,u8),
    IPv6(String),
}
fn main() {
    let mut v:Vec<Address> = Vec::new();
    v.push(Address::NoIP);
    v.push(Address::IPv4(1,2,3,4));
    
    println!("{:#?}",v[1]);
}  

into_iter().enumerate()

1
2
3
4
5
6
7
fn main() {
    let v = vec![3,2,4];
    for (idx, num) in v.into_iter().enumerate() {
      println!("index={}, value={}", idx, num);
    }

}