A question about vectors

Hello,
When I use push, then it will move to the next item automatically?

fn main() {
let mut x = vec![0;10];
let mut counter = 0;
for i in 0..10 {
	if (i % 2) == 0 {
		x.push(i);
		println!("{}",x[counter]);
		counter+=1;
		}
	}
}


Which part of the above code is wrong?

Thank you.

Your x contained ten zeroes at the beginning. You can start with x as empty Vec:

-    let mut x = vec![0;10];
+    let mut x = vec![];

(Playground)

1 Like

No. The push method doesn't have any side effect; the only thing that it does is to append a value to the end of the vector.

What your code is doing is the following (annotated with comments):

fn main() {
let mut x = vec![0;10]; // Create a mutable vector with 10 elements of value 0.
let mut counter = 0; // Define a mutable variable named counter, which is an integer and its initial value is 0
for i in 0..10 { // Loop through the following code 10 times (from i == 0 until i == 9).
	if (i % 2) == 0 { // Conditional branch met if the remainder of i divided by 2 is 0
		x.push(i); // Push the value of i to the vector "x"
		println!("{}",x[counter]); // print the value of the element in vector "x" at the position of the current value of the variable "counter"
		counter+=1; // Increment counter by 1
		}
	} // End of the conditional branch
} // End of the loop
1 Like

Or, if the vector should have a capacity of 10, one can use Vec::with_capacity(10) (docs).

Hello,
Thank you so much for your reply.
I used a counter variable, and it starts from zero. Why it shows all items as 0?

Hello,
Thank you so much for your reply.
The x.push(i);, push the value of i to the vector x, but which position? Shouldn't it start from zero?

Because the first 10 entries are 0.

1 Like

No, it appends at the end. You already created a vector of 10 elements.

1 Like

Hello,
Thank you so much for your reply.
So, the results are located from 10 to... .

You can always print the whole array with println!("{:?}", x). Hope this helps you explore what your code does.

1 Like

Hello,
Thank you for your help.
Why something like x[counter].push(i); doesn't exist?

Are you looking for insert?

I dont know c++ well and I expect this syntax is not valid there. Java has List.add for this.

1 Like

Thanks all.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.