\$\begingroup\$
\$\endgroup\$
I have a Vec with value default [0], and then I want to append into the vec with an iterator which is read from stdin, now my code is not performant since I use an insert to shift all the values behind index 0, how to improve this code with rusty style?
#[allow(unused_imports)]
use std::cmp::{max, min};
use std::io::{stdin, stdout, BufWriter, Write};
#[derive(Default)]
struct Scanner {
buffer: Vec<String>,
}
impl Scanner {
fn next<T: std::str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buffer.pop() {
return token.parse().ok().expect("Failed parse");
}
let mut input = String::new();
stdin().read_line(&mut input).expect("Failed read");
self.buffer = input.split_whitespace().rev().map(String::from).collect();
}
}
}
fn main() {
let mut scan = Scanner::default();
let n: usize = scan.next();
// How to improve these lines?
let mut arr = (0..n).map(|i| scan.next()).collect();
arr.insert(0, 0);
}
prehistoricpenguinprehistoricpenguin
asked Apr 12, 2021 at 6:20
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
Use Extend<T>
:
let mut arr = vec![0];
arr.extend((0..n).map(|_i| scan.next::<i32>()));
// must provide the explicit type: ^^^^^^^
Or resize_with
:
let mut arr = vec![0];
arr.resize_with(n + 1, || scan.next())
answered Apr 12, 2021 at 11:54
-
\$\begingroup\$ It's cool! Rust is such an expressive language! \$\endgroup\$prehistoricpenguin– prehistoricpenguin2021年04月12日 11:59:23 +00:00Commented Apr 12, 2021 at 11:59
-
1\$\begingroup\$ Code Only reviews lack an explanation of how and/or why the code being suggested is better than the OP, please explain how and why you would implement your solution, this helps us all understand how and why your code is better in this situation. Please see our Help Section on How To Give Good Answer \$\endgroup\$Malachi– Malachi2021年04月12日 14:05:23 +00:00Commented Apr 12, 2021 at 14:05
lang-rust