Create a two-dimensional array at runtime: Difference between revisions

Content added Content deleted
(→‎{{header|Rust}}: Added Rust)
m (→‎{{header|Rust}}: Added comment explanations)
Line 1,943: Line 1,943:
assert!(rows != 0 && cols != 0);
assert!(rows != 0 && cols != 0);


// Creates a vector of vectors with all elements initialized to 0.
let mut v = initialize_vec(|_| initialize_vec(|_| 0, cols), rows);
let mut v = init_vec(|| init_vec(|| 0, cols), rows);
v[rows-1][cols-1] = 4;
v[rows-1][cols-1] = 4;
println!("{}", v[rows-1][cols-1]);
println!("{}", v[rows-1][cols-1]);
Line 1,950: Line 1,951:
}
}


// Returns a dynamically-allocated array of size `n`,
fn initialize_vec<F,T>(f: F, size: usize) -> Vec<T>
// initialized with the values computed by `f`
where F: Fn(usize) -> T

fn init_vec<F,T>(f: F, n: usize) -> Vec<T>
where F: Fn() -> T
{
{
let mut vec = Vec::with_capacity(size);
let mut vec = Vec::with_capacity(n);
for i in 0..size {
for i in 0..n {
vec.push(f(i));
vec.push(f());
}
}
vec
vec