rust 数组

2022-11-30  本文已影响0人  球果假水晶蓝
let arr:[i32;4] = [1,2,3,4];
let arr = [1;4]  # let arr = [1,1,1,1]
# 遍历方法1
for i in 0..4 {
      println!("i is: {} & value is : {}",i,arr[index]);
}
# 遍历方法2 转化为迭代器,不能改变值
for val in arr.iter(){
      println!("value is :{}",val);
}
for val in arr.into_iter(){
      println!("value is :{}",val);
}
for val in arr.iter_mut(){
      println!("value is :{}",val);
}

动态数组
let a: Vec<i32> = Vec::new();
let a = vec![1,2,3,4];
let a = vec![1;4];
for i in &a {
        println!("{}", i);
}
for i in &mut a {
        *i += 50;
}
a.insert(0,100); # 插入数据
a.push(1); # 尾部插入
a.len() # 数组的长度
a.capacity() # 数组的容量
let mut vec = Vec::with_capacity(1); # 设置数组的容量大小
a.remove(1); # 去除某位置元素
a.clear() # 清除所有数据,长度变为0
a.swap(1,2) # 交换索引1 和索引2位置的数字
a.sort() # 从小到大排序
a.reverse(); 
fn main() {
    let mut vec = vec![0, 1, 2, 3, 4];
    vec.extend([44, 55]);
    println!("{vec:?}");
}
fn main() {
    let mut vec = vec![0, 1, 2, 3, 4];
    vec.extend_from_slice(&[44, 55]);
    println!("{vec:?}");
}

let mut vec2 :Vec<i32> = (1..=10).collect(); # 生成可变数组
vec2.retain(|&x| x % 2 == 0); # 使用retain 去过滤
println!("{:?}",vec2);

# 浮点型数据排序
let mut vec_f = vec!();
let mut v_1 = 1.0f64;
for i in 1..=10 {
        vec_f.push(v_1);
        v_1 += 1.0;
}
vec_f.sort_by(|a, b| b.partial_cmp(a).unwrap());
println!("{:?}",vec_f);

迭代器
let vec = vec![0, 1, 2, 3, 4];
let result: i32 = vec.iter().product(); # 求积
let result: i32 = vec.iter().sum(); # 求和
let result:Vec<i32>  = vec.iter().rev().map(|&x| x).collect();
let result  = vec.iter().rev();
let result = vec.iter().max();
let result = vec.iter().min();
vec.iter().rev().for_each(|e| println!("{e:?}"));
let value = vec.iter().last() #  取迭代器最后一个元素
let value = vec.iter().nth(2)) #  取迭代器第二个元素
let zip = vec1.iter().zip(&vec2)
let chain = vec1.iter().chain(&vec2);
fn main() {
    let vec = vec![0, 1, 2, 3, 4,5];
    let result = vec.iter().step_by(2).find(|&e| e > &2);
    println!("{result:?}");
}
fn main() {
    let vec1 = vec![0, 1, 2, 3, 4];
    let vec2 = vec![5, 6, 7, 8, 9];
    let chain = vec1.iter().chain(&vec2);
    println!("{:?}", chain);
}



上一篇下一篇

猜你喜欢

热点阅读