-
Notifications
You must be signed in to change notification settings - Fork 1.1k
collections/vector #214
-
collections/vector
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 17 -
😄 2 -
🎉 1 -
😕 5 -
❤️ 1 -
🚀 4
Replies: 23 comments 5 replies
-
v2.extend(v1.iter());
Beta Was this translation helpful? Give feedback.
All reactions
-
❤️ 1
-
v2.extend(&v1);
Beta Was this translation helpful? Give feedback.
All reactions
-
好多都没学过 ,我不知道怎么做
Beta Was this translation helpful? Give feedback.
All reactions
-
+1
Beta Was this translation helpful? Give feedback.
All reactions
-
+1
Beta Was this translation helpful? Give feedback.
All reactions
-
在练中学,在学中练
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2 -
🚀 1
-
Done.
Beta Was this translation helpful? Give feedback.
All reactions
-
2022年12月6日 发现 solution 和题目对不上,这边补充下第三题的答案(只能保证可以跑,仅供参考)
// 填空 fn main() { // array -> Vec // impl From<[T; N]> for Vec let arr = [1, 2, 3]; let v1 = Vec::from(arr); let v2: Vec<i32> = arr.into(); assert_eq!(v1, v2); // String -> Vec // impl From<String> for Vec let s = "hello".to_string(); let v1: Vec<u8> = s.into(); let s = "hello".to_string(); let v2 = s.into_bytes(); assert_eq!(v1, v2); // impl<'_> From<&'_ str> for Vec let s = "hello"; let v3 = Vec::from(s); assert_eq!(v2, v3); // 迭代器 Iterators 可以通过 collect 变成 Vec let v4: Vec<i32> = [0; 10].iter().map(|x| *x).collect(); assert_eq!(v4, vec![0; 10]); println!("Success!") }
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2
-
第五题
// 修复错误 fn main() { let mut v = vec![1, 2, 3]; let slice1 = &v[..]; // 越界访问将导致 panic. // 修改时必须使用 `v.len` let slice2 = &v[0..v.len()]; assert_eq!(slice1, slice2); // 切片是只读的 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec` let vec_ref: &mut Vec<i32> = &mut v; (*vec_ref).push(4); let mut slice3: Vec<i32> = Vec::from(&v[..3]); slice3.push(4); assert_eq!(slice3, &[1, 2, 3, 4]); println!("Success!") }
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2
-
mark
Beta Was this translation helpful? Give feedback.
All reactions
-
第四题我的做法。忘了用if let了,会比match更简洁。
fn main() { let mut v = Vec::from([1, 2, 3]); for i in 0..5 { match v.get(i) { Some(num)=>{ println!("{:?}", num); v[i]=num+1; }, None=>v.push(i+2) } } assert_eq!(v, vec![2, 3, 4, 5, 6]); println!("Success!") }`
Beta Was this translation helpful? Give feedback.
All reactions
-
fn main() { let mut v = Vec::from([1, 2, 3]); for i in 0..5 { if let Some(num) = v.get(i) { println!("{:?}", num); v[i] = num + 1; } else { v.push(i + 2) } } assert_eq!(v, vec![2, 3, 4, 5, 6]); println!("Success!") }
Beta Was this translation helpful? Give feedback.
All reactions
-
lala
Beta Was this translation helpful? Give feedback.
All reactions
-
1、回顾一下对于Vec
的遍历,以及其所有权
fn main() { let arr: [u8; 3] = [1, 2, 3]; let v = Vec::from(arr); is_vec(v.clone()); let v = vec![1, 2, 3]; is_vec(v.clone()); // vec!(..) 和 vec![..] 是同样的宏,宏可以使用 []、()、{}三种形式,因此... let v = vec!(1, 2, 3); is_vec(v.clone()); // ...在下面的代码中, v 是 Vec<[u8; 3]> , 而不是 Vec<u8> // 使用 Vec::new 和 `for` 来重写下面这段代码 let mut v1=Vec::new(); for a in arr{ v1.push(a); } is_vec(v1.clone()); assert_eq!(v, v1); println!("Success!") } fn is_vec(v: Vec<u8>) {}
2、Vec
可以用extend
来进行拓展
fn main() { let mut v1 = Vec::from([1, 2, 4]); v1.pop(); v1.push(3); let mut v2 = Vec::new(); v2.extend(v1.clone());//这里不clone的话会导致v1失去所有权 assert_eq!(v1, v2); println!("Success!") }
3、array
可以通过.into()
变成Vec
,或者使用Vec::from()
进行转换;Iterator
可以通过collect
变成 Vec
fn main() { // array -> Vec // impl From<[T; N]> for Vec let arr = [1, 2, 3]; let v1 = Vec::from(arr); let v2: Vec<i32> = arr.into(); assert_eq!(v1, v2); // String -> Vec // impl From<String> for Vec let s = "hello".to_string(); let v1: Vec<u8> = s.into(); let s = "hello".to_string(); let v2 = s.into_bytes(); assert_eq!(v1, v2); // impl<'_> From<&'_ str> for Vec let s = "hello"; let v3 = Vec::from(s); assert_eq!(v2, v3); // 迭代器 Iterators 可以通过 collect 变成 Vec let v4: Vec<i32> = [0; 10].into_iter().collect(); assert_eq!(v4, vec![0; 10]); println!("Success!") }
4、索引
fn main() { let mut v = Vec::from([1, 2, 3]); for i in 0..3 { println!("{:?}", v[i]) } for i in 0..5 { // 实现这里的代码... if i<=2{ v[i]+=1; }else{ v.push(i+2); } } assert_eq!(v, vec![2, 3, 4, 5, 6]); println!("Success!") }
5、Vec
中的切片
fn main() { let mut v = vec![1, 2, 3]; let slice1 = &v[..]; // 越界访问将导致 panic. // 修改时必须使用 `v.len` let slice2 = &v[0..v.len()]; assert_eq!(slice1, slice2); // 切片是只读的 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec` let vec_ref: &mut Vec<i32> = &mut v; (*vec_ref).push(4); let slice3 = &vec_ref[0..4]; //slice3.push(4); assert_eq!(slice3, &[1, 2, 3, 4]); println!("Success!") }
6、len
和capacity
的区别
fn main() { let mut vec = Vec::with_capacity(10); assert_eq!(vec.len(), 0); assert_eq!(vec.capacity(), 10); // 由于提前设置了足够的容量,这里的循环不会造成任何内存分配... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert_eq!(vec.capacity(), 10); // ...但是下面的代码会造成新的内存分配 vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // 填写一个合适的值,在 `for` 循环运行的过程中,不会造成任何内存分配 let mut vec = Vec::with_capacity(100); for i in 0..100 { vec.push(i); } assert_eq!(vec.len(),100); assert_eq!(vec.capacity(), 100); println!("Success!") }
7、用枚举对象在Vec中存储不同的类型
#[derive(Debug,PartialEq)]//注意此处需要实现PartialEq enum IpAddr { V4(String), V6(String), } fn main() { // 填空 let v : Vec<IpAddr>= Vec::from([ IpAddr::V4("127.0.0.1".to_string()), IpAddr::V6("::1".to_string()) ]); // 枚举的比较需要派生 PartialEq 特征 assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string())); assert_eq!(v[1], IpAddr::V6("::1".to_string())); println!("Success!") }
8、实现同一个特征的可以用Box
封装起来,然后作为同一个Vec
元素
trait IpAddr { fn display(&self); } struct V4(String); impl IpAddr for V4 { fn display(&self) { println!("ipv4: {:?}",self.0) } } struct V6(String); impl IpAddr for V6 { fn display(&self) { println!("ipv6: {:?}",self.0) } } fn main() { // 填空 let v: Vec<Box<dyn IpAddr>>= vec![ Box::new(V4("127.0.0.1".to_string())), Box::new(V6("::1".to_string())), ]; for ip in v { ip.display(); } }
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1
-
done
Beta Was this translation helpful? Give feedback.
All reactions
-
7好阴哦
Beta Was this translation helpful? Give feedback.
All reactions
-
到这期确实变难了不少。
Beta Was this translation helpful? Give feedback.
All reactions
-
let v4: Vec<i32> = [0; 10].into_iter().collect();
This will produce error:
value of type `Vec<i32>` cannot be built from `std::iter::Iterator<Item=&{integer}>`
Solutions:
let v4: Vec<i32> = [0; 10].iter().copied().collect();
-> https://stackoverflow.com/a/64200786
Or:
let v4: Vec<i32> = IntoIterator::into_iter([0; 10]).collect();
Beta Was this translation helpful? Give feedback.
All reactions
-
down
Beta Was this translation helpful? Give feedback.
All reactions
-
- done
Beta Was this translation helpful? Give feedback.
All reactions
-
mark 11.2 5
Beta Was this translation helpful? Give feedback.
All reactions
-
done~~~
Beta Was this translation helpful? Give feedback.
All reactions
-
mark finished
Beta Was this translation helpful? Give feedback.
All reactions
-
难起来了
Beta Was this translation helpful? Give feedback.
All reactions
-
Day 9
Done✅
Beta Was this translation helpful? Give feedback.
All reactions
-
第一题
fn main() { let arr: [u8; 3] = [1, 2, 3]; let v = Vec::from(arr); is_vec(&v); let v = vec![1, 2, 3]; is_vec(&v); // vec!(..) 和 vec![..] 是同样的宏,宏可以使用 []、()、{}三种形式,因此... let v = vec!(1, 2, 3); is_vec(&v); // ...在下面的代码中, v 是 Vec<[u8; 3]> , 而不是 Vec<u8> // 使用 Vec::new 和 `for` 来重写下面这段代码 // let v1 = vec!(arr); let mut v1 = Vec::new(); for i in &arr { v1.push(*i); } is_vec(&v1); assert_eq!(v, v1); println!("Success!") } fn is_vec(v: &Vec<u8>) {}
第二题
// 填空 fn main() { let mut v1 = Vec::from([1, 2, 4]); v1.pop(); v1.push(3); let mut v2 = Vec::new(); v2.extend([1,2,3]); assert_eq!(v1, v2); println!("Success!") }
第三题
// 填空 fn main() { // array -> Vec // impl From<[T; N]> for Vec let arr = [1, 2, 3]; let v1 = Vec::from(arr); let v2: Vec<i32> = arr.to_vec(); assert_eq!(v1, v2); // String -> Vec // impl From<String> for Vec let s = "hello".to_string(); let v1: Vec<u8> = s.into(); let s = "hello".to_string(); let v2 = s.into_bytes(); assert_eq!(v1, v2); // impl<'_> From<&'_ str> for Vec let s = "hello"; let v3 = Vec::from(s); assert_eq!(v2, v3); // 迭代器 Iterators 可以通过 collect 变成 Vec let v4: Vec<i32> = [0; 10].into_iter().collect(); assert_eq!(v4, vec![0; 10]); println!("Success!") }
第四题
// 修复错误并实现缺失的代码 fn main() { let mut v = Vec::from([1, 2, 3]); for i in 0..3 { println!("{:?}", v[i]) } v.clear(); for i in 2..7 { // 实现这里的代码... v.push(i); } assert_eq!(v, vec![2, 3, 4, 5, 6]); println!("Success!") }
第五题
// 修复错误 fn main() { let mut v = vec![1, 2, 3]; let slice1 = &v[..]; // 越界访问将导致 panic. // 修改时必须使用 `v.len` let slice2 = &v[0..v.len()]; assert_eq!(slice1, slice2); // 切片是只读的 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec` let vec_ref: &mut Vec<i32> = &mut v; (*vec_ref).push(4); let slice3 = &mut Vec::from(&v[0..3]); slice3.push(4); assert_eq!(slice3, &[1, 2, 3, 4]); println!("Success!") }
第六题
// 修复错误 fn main() { let mut vec = Vec::with_capacity(10); assert_eq!(vec.len(), 0); assert_eq!(vec.capacity(), 10); // 由于提前设置了足够的容量,这里的循环不会造成任何内存分配... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert_eq!(vec.capacity(), 10); // ...但是下面的代码会造成新的内存分配 vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // 填写一个合适的值,在 `for` 循环运行的过程中,不会造成任何内存分配 let mut vec = Vec::with_capacity(101); for i in 0..100 { vec.push(i); } assert_eq!(vec.len(), 100); assert_eq!(vec.capacity(), 101); println!("Success!") }
第七题
#[derive(Debug, PartialEq)] enum IpAddr { V4(String), V6(String), } fn main() { // 填空 let v : Vec<IpAddr>= vec![ IpAddr::V4("127.0.0.1".to_string()), IpAddr::V6("::1".to_string()), ]; // 枚举的比较需要派生 PartialEq 特征 assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string())); assert_eq!(v[1], IpAddr::V6("::1".to_string())); println!("Success!") }
第八题
trait IpAddr { fn display(&self); } struct V4(String); impl IpAddr for V4 { fn display(&self) { println!("ipv4: {:?}",self.0) } } struct V6(String); impl IpAddr for V6 { fn display(&self) { println!("ipv6: {:?}",self.0) } } fn main() { // 填空 let v: Vec<Box<dyn IpAddr>>= vec![ Box::new(V4("127.0.0.1".to_string())), Box::new(V6("::1".to_string())), ]; for ip in v { ip.display(); } }
Beta Was this translation helpful? Give feedback.
All reactions
-
done
Beta Was this translation helpful? Give feedback.
All reactions
-
done
Beta Was this translation helpful? Give feedback.