我想创建一个函数,返回一个数据结构,其中包含某组数字的所有可能组合:例如:对于[1, 2, 3]
,返回[[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
}
我得到的错误是:
error[E0308]: mismatched types
--> src/main.rs:10:26
|
10 | actions.push(c);
| ^ expected u32, found &{integer}
|
= note: expected type `std::vec::Vec<u32>`
found type `std::vec::Vec<&{integer}>`
error[E0308]: mismatched types
--> src/main.rs:14:30
|
14 | actions.push(p);
| ^ expected u32, found &{integer}
|
= note: expected type `std::vec::Vec<u32>`
found type `std::vec::Vec<&{integer}>`
编辑:尝试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>`
尝试
actions.push(c.iter().cloned().collect())
时返回以下错误。。。
之所以会发生这种情况,是因为c
是Vec<&u32>
,而.iter()
在对项的引用上进行迭代,所以c.iter()
是&&u32
s上的迭代器。.cloned()
删除了其中一个&
s,但不删除第二个。您可以通过添加另一个.cloned()
(或.copied()
(来解决此问题,但我更喜欢使用.map
:
actions.push(c.iter().map(|c| **c).collect());
如果您不需要保留引用,您可以使用Vec<u32>
对c
进行阴影处理,以便在循环中使用:
let c: Vec<u32> = c.into_iter().cloned().collect();
cloned
在这里起作用是因为c.into_iter()
与c.iter()
不同,它使用Vec<u32>
在u32
s上返回迭代器。
我也看不出有什么好的理由在这里使用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
}
actions.push(p)
在没有.into_iter().cloned().collect()
的情况下工作,因为permutator::HeapPermutationIterator
在内部进行克隆。
我找到了一种非常丑陋的方法来解决这个问题,但由于我是该语言的新手,这是我能想到的最好的方法。
主要问题似乎是我有一个引用整数的Vec,而不是整数的Vector,所以我用一个临时变量改变了它:
let mut temp:Vec<u32> = vec![];
for z in c.iter(){
temp.push(**z);
}
actions.push(temp);