'How to combine two vectors of references without consuming an iterator?
I want to combine two reference vectors and convert them into a vector of values without consuming an iterator.
Situation:
Generate vectors by iterating over specific combinations. (2 elements from one vector, 2 elements from another vector)
- Code:
use core::iter::Iterator;
use itertools::Itertools;
fn main() {
let vec_a: Vec<u8> = vec![1, 2, 3];
let vec_b: Vec<u8> = vec![4, 5, 6];
// a: Vec<&u8>
for a in vec_a.iter().combinations(2) {
// b: Vec<&u8>
for b in vec_b.iter().combinations(2) {
// c: Vec<u8> <- a + b
let c: Vec<u8> = a.clone().into_iter().chain(b).cloned().collect();
println!("a: {:?}, b: {:?}, c: {:?}", a, b, c);
}
}
}
- Expected output:
a: [1, 2], b: [4, 5], c: [1, 2, 4, 5]
a: [1, 2], b: [4, 6], c: [1, 2, 4, 6]
a: [1, 2], b: [5, 6], c: [1, 2, 5, 6]
a: [1, 3], b: [4, 5], c: [1, 3, 4, 5]
a: [1, 3], b: [4, 6], c: [1, 3, 4, 6]
a: [1, 3], b: [5, 6], c: [1, 3, 5, 6]
a: [2, 3], b: [4, 5], c: [2, 3, 4, 5]
a: [2, 3], b: [4, 6], c: [2, 3, 4, 6]
a: [2, 3], b: [5, 6], c: [2, 3, 5, 6]
P.S.
I read the following link before posting my question. However, the answer to this question consumes Vec
and its iterator, so it did not work in this situation.
Solution 1:[1]
Thanks to @ChayimFriedman.
There are some ways to do this.
Without consumption
// a: Vec<&u8> // b: Vec<&u8> let c: Vec<u8> = a.iter().chain(&b).copied().copied().collect(); println!("a: {:?}", a); println!("b: {:?}", b);
With consumption
// a: Vec<&u8> // b: Vec<&u8> let c: Vec<u8> = a.into_iter().chain(b).copied().collect(); // println!("a: {:?}", a); -> compile error // println!("b: {:?}", b); -> compile error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |