Background
I have a vec, and my algorithms requires that in each round, I will iterate the vec and do a filter on each elements, and the round will finish when the vec's length is stable.
To implement this algorithm, it is nature to have two vecs: ori
and tmp
. The pseudocode looks like
let mut tmp = Vec::with_capacity(ori.len());
loop {
let prev_round_length = ori.len();
for ele in ori /* Here needs help! */ {
if filter(&ele) {
tmp.push(ele);
}
}
std::mem::swap(&mut tmp, &mut ori);
let cur_round_length = ori.len();
if cur_round_length == prev_round_length {
break;
}
}
Problem
The for ele in ori
is where I need help. In this pseudocode, this for
-loop needs to meet several requirements:
- The ownership of
ori
should not be taken
Sinceori
needs to be swapped withtmp
later. - The ownership of all elements of
ori
should be taken
Since they would be pushed intotmp
later. - The capacity of
ori
should not be shrunk
We shall make suretmp
andori
does not require additional resize in the loop, since it is unnecessary (The maximum length is already known before the loop).
For now, I can only use while let Some(ele) = ori.pop()
to work around, since the documentation of pop
does not mention the resize, so I could assume pop
does not lead to ori
's capacity shrinking.
However, I don't think it is a graceful pattern. Is there any better ways to achieve this?