 # How to perform assignment to part of Vec instead of using loop

What I'd like to do is to assign the same value to part of a Vec.
Given that:
let mut a = vec![0;10];
I'd like to assign 1 to a[..3], assign 2 to a[3..9] and assign 3 to a[9..].
Is there any solution instead of using loop?

``````let mut a = vec![0; 10];
a[..3].copy_from_slice(&[1; 3]);
a[3..9].copy_from_slice(&[2; 6]);
a = 3;
``````

But it looks strange for me... looks like much unnecessary work is done here. I would prefer just:

``````let a = vec![1, 1, 1, 2, 2, 2, 2, 2, 2, 4];
``````
1 Like

Actually, what I described is just a concrete example.
Which part should be assigned to what value is known at runtime.
Assuming that

`let arr1 = vec![2,3,1,3,2,4,6,9,2];`
`let arr2 = vec![2,1,4,3,9,6];`

I need to create a Vec arr3 by sorting arr1 in relative order of arr2, which should be

[2,2,2,1,4,3,3,9,6]

I get amount of each element in arr2 by a HashMap, then I need to assign values to parts of arr3. while loop in line 37-40 is my solution.

You can replace that `while` loop with `for` loop. Anyway, is there a reason to avoid loop here?

``````for i in 0..cnt {
ret[bet +i] = elem;
}
``````

Perhaps you would find using a helper function cleaner?

``````fn assign_all<T: Copy>(slice: &mut [T], value: T) {
for ptr in slice {
*ptr = value;
}
}

fn main() {
let mut a = vec![0; 10];
assign_all(&mut a[..3], 1);
assign_all(&mut a[3..9], 2);
assign_all(&mut a[9..], 3);
}
``````

It seems that avoiding loop here is not appropriate.

``````let mut a = vec![];
for k in arr2 {
let v = map.get(k).unwrap();
a.extend(std::iter::repeat(k).take(v));
}
``````

It's elegant, but how about their time complexity especially for its extending empty Vec other than allocating space first?

just use `with_capacity` method on `Vec`.

``````let mut a = Vec::with_capacity(n);
``````

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.