How to initialize a vector of usize with a dummy value?

Hi all,

In my program I want to save the index values of a vector (u) in some other vector (v). But this
I want this vector (v) initialized with -1. So that I can compare with to know when to stop it.

I am doing

let v = vec![1, 2, 3];
let mut u = vec![-1, -1, -1];
u[0] = 2;
println!("{}", v[u[0]]);

This doesn't work.

I know that u has to be of usize, and it doesn't support negative values. Is there any other way to do it?
Or are there any dummy values to initialize the usize vector?

How about usize::max_value()

The main algorithm goes as

// some random vector
let v = vec![1., 3., 5., 2.3, 22., 0., 9.];
// vector holding the indices of vector v (with some condition)
let u = vec![4, 3, 5, 2, 1, -1, -1];
let indices = vec![];
let mut next = 0;
while next != -1 {
    indices.append(next);
    next = u[next];
}

The result will be

indices = vec![0, 4, 1, 3, 2, 5];

I see that usize::max_value works, just in case can I have some other solution, provided the above algorithm.

Could you use an Option<usize> for this?

1 Like

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