How do I initialize a vector from 0
to n
in Rust? Is there another way of doing that than creating an empty vector and invoking push
inside a loop?
I prefer a one-liner.
A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.
You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.
This post will discuss how to initialize a vector with a sequential range 1 to n in C++. 1. Using std::iota The std::iota function assigns consecutive values to every element in the specified range. It can be used as follows to fill a vector with successive values starting from 1 till n.
Initialize a vector in C++ (5 different ways) Following are different ways to create and initialize a vector in C++ STL. Initializing by one by one pushing values : // CPP program to create an empty vector. // and one by one push values. #include <bits/stdc++.h>. using namespace std;
In an array we can do int arr [100]= {0} ,this initializes all the values in the array to 0. I was trying the same with vector like vector <int> v (100)= {0} ,but its giving the error error: expected ‘,’ or ‘;’ before ‘=’ token.
Using std::iota The std::iota function assigns consecutive values to every element in the specified range. It can be used as follows to fill a vector with successive values starting from 1 till n.
A range can be collected into a vector:
pub fn sequence(n: u32) -> Vec<u32> {
(0..n).collect()
}
Playground
Here is how you can do it as a one-liner:
let n = 4;
let v: Vec<i32> = (0..n).collect(); // the last element will be n-1
assert_eq!(v, vec![0, 1, 2, 3]);
let v: Vec<i32> = (0..=n).collect(); // the last element will be n
assert_eq!(v, vec![0, 1, 2, 3, 4]);
Or, alternatively:
let v: Vec<i32> = Vec::from_iter(0..n); // the last element will be n-1
assert_eq!(v, vec![0, 1, 2, 3]);
let v: Vec<i32> = Vec::from_iter(0..=n); // the last element will be n
assert_eq!(v, vec![0, 1, 2, 3, 4]);
Instead of i32
we could use other numeric types like u8
, u16
, i8
, etc. That's because both collect()
and Vec::from_iter
are generic methods.
All those solutions make use of the Range or RangeInclusive structs respectively, both of which implement Iterator. That allows them to easily be converted into a Vec, which is most often done via the collect()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With