Mig*_*uel 4 types vector slice rust
我想创建一个函数,返回一个数据结构,其中包含特定一组数字的所有可能组合:例如: for [1, 2, 3]return [[1], [2], [3], [1, 2], [2,1], ..., [1, 2, 3], [2, 1, 3], ...[3, 2, 1]]。
我理解 和c是p的某种向量&integer,但我找不到将它们保存到数组或向量中的方法。我试图将其保存为向量的向量,因为我认为不可能将它们保存为数组的向量,因为数组具有不同的大小。它也不可能作为向量数组,因为我不知道开始时的组合数量。
如何将所有c和存储p在数据结构中,以便可以在外部返回和使用?
use permutator::{Combination, Permutation}; // 0.3.3
pub fn init() -> Vec<Vec<u32>> {
let actions: Vec<Vec<u32>>;
let mut data = &[1, 2, 3];
let mut counter = 1;
for i in 1..=data.len() {
data.combination(i).for_each(|mut c| {
println!("{:?}", c);
actions.push(c);
c.permutation().for_each(|p| {
println!("k-perm@{} = {:?}", counter, p);
counter += 1;
actions.push(p);
});
});
}
actions
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误是:
use permutator::{Combination, Permutation}; // 0.3.3
pub fn init() -> Vec<Vec<u32>> {
let actions: Vec<Vec<u32>>;
let mut data = &[1, 2, 3];
let mut counter = 1;
for i in 1..=data.len() {
data.combination(i).for_each(|mut c| {
println!("{:?}", c);
actions.push(c);
c.permutation().for_each(|p| {
println!("k-perm@{} = {:?}", counter, p);
counter += 1;
actions.push(p);
});
});
}
actions
}
Run Code Online (Sandbox Code Playgroud)
编辑:
尝试时actions.push(c.iter().cloned().collect())返回以下错误:
error[E0277]: a collection of type `std::vec::Vec<u32>` cannot be built from an iterator over elements of type `&u32`
--> src/rl.rs:59:44
|
59 | actions.push(c.iter().cloned().collect());
| ^^^^^^^ a collection of type `std::vec::Vec<u32>` cannot be built from `std::iter::Iterator<Item=&u32>`
|
= help: the trait `std::iter::FromIterator<&u32>` is not implemented for `std::vec::Vec<u32>`
Run Code Online (Sandbox Code Playgroud)
尝试时
actions.push(c.iter().cloned().collect())返回以下错误...
发生这种情况是因为c是 a Vec<&u32>,并且.iter()迭代对项的引用,因此c.iter()是 s 上的迭代器&&u32。.cloned()删除其中之一&,但不删除第二个。您可以通过添加另一个.cloned()(或.copied())来解决此问题,但我更喜欢使用.map:
actions.push(c.iter().map(|c| **c).collect());
Run Code Online (Sandbox Code Playgroud)
如果您不需要保留引用,则可以使用ca 来代替阴影Vec<u32>以在循环内使用:
let c: Vec<u32> = c.into_iter().cloned().collect();
Run Code Online (Sandbox Code Playgroud)
cloned在这里起作用是因为c.into_iter()与 不同c.iter(),使用Vec<u32>来返回 s 上的迭代器u32。
我也没有看到for_each在这里使用代替常规for循环的充分理由。我建议这样写init:
pub fn init() -> Vec<Vec<u32>> {
let actions: Vec<Vec<u32>>;
let data = &[1, 2, 3];
let mut counter = 1;
for i in 1..=data.len() {
for c in data.combination(i) {
let mut c = c.into_iter().cloned().collect();
println!("{:?}", c);
actions.push(c.clone());
for p in c.permutation() {
println!("k-perm@{} = {:?}", counter, p);
counter += 1;
actions.push(p);
}
}
}
actions
}
Run Code Online (Sandbox Code Playgroud)
actions.push(p)在这里工作没有.into_iter().cloned().collect()因为permutator::HeapPermutationIterator内部克隆。