# 动态数组Vec

## 特性及声明方式

### new

let mut v1: Vec<i32> = Vec::new();

let mut v1 = Vec::new::<i32>();
// 与之对比的,collect函数就能指定：
// let mut v2 = (0i32..5).collect::<Vec<i32>>();

### 宏声明

let v: Vec<i32> = vec![];

// 以下语句相当于：
// let mut temp = Vec::new();
// temp.push(1);
// temp.push(2);
// temp.push(3);
// let v = temp;
let v = vec![1, 2, 3];

let v = vec![0; 10]; //注意分号，这句话声明了一个 内容为10个0的动态数组

### 从迭代器生成

let v: Vec<_> = (1..5).collect();

## 访问及修改

### 随机访问

let a = vec![1, 2, 3];
assert_eq!(a[1usize], 2);

let v =vec![1, 2, 3];
assert_eq!(v.get(1), Some(&2));
assert_eq!(v.get(3), None);

### 迭代器

let v = vec![1, 2, 3];
for i in &v { .. } // 获得引用
for i in &mut v { .. } // 获得可变引用
for i in v { .. } // 获得所有权，注意此时Vec的属主将会被转移！！

### push的效率研究

use std::time;

fn push_1m(v: &mut Vec<usize>, total: usize) {
let e = time::SystemTime::now();
for i in 1..total {
v.push(i);
}
let ed = time::SystemTime::now();
println!("time spend: {:?}", ed.duration_since(e).unwrap());
}

fn main() {
let mut v: Vec<usize> = vec![];
push_1m(&mut v, 5_000_000);
let mut v: Vec<usize> = vec![];
v.reserve(5_000_000);
push_1m(&mut v, 5_000_000);
}

➜  debug git:(master) ✗ time ./demo
time spend: Duration { secs: 0, nanos: 368875346 }
time spend: Duration { secs: 0, nanos: 259878787 }
./demo  0.62s user 0.01s system 99% cpu 0.632 total


➜  release git:(master) ✗ time ./demo
time spend: Duration { secs: 0, nanos: 53389934 }
time spend: Duration { secs: 0, nanos: 24979520 }
./demo  0.06s user 0.02s system 97% cpu 0.082 total