Rust中的狭义的Vec,相当于一些其它语言可变长度的List,ArrayList,Array(Julia语言),是核心的数据结构。一般通过以下方式生成:
let vec = vec![1,2,3];
let vec:Vec<i32> =vec![1,2,3];//Vec<i32>也可不加,可以推断出来
或
let data =Vec::new();
或
let data:Vec<i32> =Vec::new();//Vec<i32>具体看后面的应用
如果广义上的vector,分动态数组和固定数组,有必要了解一下:
let mut vec = vec!["a", "b", "c", "d"];//动态数组
let mut array = ["a", "b", "c", "d"];//固定数组
或
let mut array:[&str;4] = ["a", "b", "c", "d"];//固定数组:
//[&str;4] :其中是分号隔开,4表示这个固定数组的长度,不可变的。
两者的相同之处:
assert_eq!(vec, array);//从目前来看,两者的值是相同的;
两者的不同之处:
//array :可以进行元素数不变下操作,包括改变其中值之类;
//array.insert(3,"e");error:没有insert这个函数
//array.push("e"); error:没有push这个函数
// vec: 不限制
下面,我们有函数是应用在动态数组上的,有些也可以应用在固定数组上的。请留意,并不要搞混了。
关于相关函数,有空大家可以仔细看了一下官方手册:
https://doc.rust-lang.org/std/vec/struct.Vec.html
其相关函数非常多,功能十分强大,能做到活学活用需要一定的时间摸索。
现在初步COPY了官方手册中主要函数的用法,具体如下:
1、get_mut()
和HashMap中有所不同,在vec中,get_mut(1)的1是第1个值(从0开始…).
let x = &mut ["a", "b", "c"];
if let Some(elem) = x.get_mut(1) {
*elem = "42";
}
assert_eq!(x,&["a","42","c"]);
2、swap: 交换特定的两个值
let mut v = ["a", "b", "c", "d"];
v.swap(1, 3);
assert!(v == ["a", "d", "c", "b"]);
3、reverse:逆序
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
4、iter_mut:循还改值
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
*elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
5、windows:有交叉的轮发
let slice = ['r', 'u', 's', 't'];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), &['r', 'u']);
assert_eq!(iter.next().unwrap(), &['u', 's']);
assert_eq!(iter.next().unwrap(), &['s', 't']);
assert!(iter.next().is_none());
如果
let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
6、chunks:无交叉的连发
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
再有:
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.chunks_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
7、split: 把符合条件的做为分隔
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
8、contains:包括
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));
9、starts_with,end_with:以…开始(结尾)
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));
注意:
let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
10、sort,sort_by,sort_by_key:排序
let mut v = [-5, 4, 1, -3, 2];
v.sort();
assert!(v == [-5, -3, 1, 2, 4]);
let mut v = [5, 4, 1, 3, 2];
v.sort_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);
// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);
let mut v = [-5i32, 4, 1, -3, 2];
v.sort_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);
11、to_vec(),into_vec()
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
let s: Box<[i32]> = Box::new([10, 40, 30]);
let x = s.into_vec();
// `s` cannot be used anymore because it has been converted into `x`.
assert_eq!(x, vec![10, 40, 30]);
12、insert,在相应个序号上insert
let mut v = vec!["a", "b", "c"];
v.insert(1, "d");//在第1个序列号上insert 元素"d"
assert_eq!(v, vec!["a", "d", "b", "c"]);
// 值相等,再次举例
assert_eq!(v, ["a", "d", "b", "c"]);
13、remove,删除第n个值
let mut v = vec!["a", "b", "c"];
assert_eq!(v.remove(1), "b");//删除第1个值(0,1,....)
14、retain: 只保留符合条件的值
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x%2 == 0);
assert_eq!(vec, [2, 4]);
15、push、pop、append
// push:对元素的压入操作
let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);
//pop:对元素的弹出操作,后进先出型
let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);
// append :两个vec之间
let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);
16、is_empty(), len
let mut v = Vec::new();
assert!(v.is_empty());
v.push(1);
assert!(!v.is_empty());
let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);
17、drain、clear
// 抽取序列号满足条件的,组成新的vec
let mut v = vec![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);
// drain(..)==clear()
v.drain(..);
assert_eq!(v, &[]);
assert!(v.is_empty());
// clear()
let mut v = vec![1, 2, 3];
v.clear();
assert!(v.is_empty());
18、truncate :截取前面<n的值
let mut n =3;
let mut vec = vec!["a", "b", "c", "d", "e"];
vec.truncate(n);//取0,1,2序列值
assert_eq!(vec, ["a", "b", "c"]);
//如果n>vec.len()-1,则会报错
19、extend、extend_from_slice
//extend
let mut vec = vec![4, 5, 6];
vec.extend([1, 2, 3].iter().cloned());//[4,5,6,1,2,3]
vec.sort();
println!("vec :{:?}", vec); //[1,2,3,4,5,6]
//extend_from_slice
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);