Blank
Blank

Reputation: 443

Read lines in pairs from stdin in rust

My input data is structured as follows:

label_1
value_1
label_2
value_2
...

And my end goal is to read that data into a HashMap

My current working approach is to put even and odd lines in two separate vectors and then read from both vectors to add to Hashmap.

use std::io;
use std::io::prelude::*;
use std::collections::HashMap;

fn main() {
    
    let mut labels: Vec<String> = Vec::new();
    let mut values: Vec<String> = Vec::new();
     
    let stdin = io::stdin();

    /* Read lines piped from stdin*/
    for (i, line) in stdin.lock().lines().enumerate() {
    
        if i % 2 == 0 {
            /* store labels (even lines) in labels vector */
            labels.push(line.unwrap());

        } else {
            /* Store values (odd lines) in values vector */
            values.push(line.unwrap());
        }
    }

    println!("number of labels: {}", labels.len());
    println!("number of values: {}", values.len());
    


    /* Zip labels and values into one iterator */
    let double_iter = labels.iter().zip(values.iter());

    /* insert (label: value) pairs into hashmap */
    let mut records: HashMap<&String, &String> = HashMap::new();
    for (label, value) in double_iter {
        records.insert(label, value);
    }
}

I would like ask how to achieve this result without going though an intermediary step with vectors ?

Upvotes: 1

Views: 2274

Answers (3)

kmdreko
kmdreko

Reputation: 59892

You can use .tuples() from the itertools crate:

use itertools::Itertools;
use std::io::{stdin, BufRead};

fn main() {
    for (label, value) in stdin().lock().lines().tuples() {
        println!("{}: {}", label.unwrap(), value.unwrap());
    }
}

See also:

  • This answer on "Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?"

Upvotes: 3

8176135
8176135

Reputation: 4133

You can manually advance an iterator with .next()

use std::io;
use std::io::prelude::*;
use std::collections::HashMap;

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let mut records = HashMap::new();

    while let Some(label) = lines.next() {
        let value = lines.next().expect("No value for label");
        records.insert(label.unwrap(), value.unwrap());
    }
}

Playground

Upvotes: 2

aurexav
aurexav

Reputation: 2865

How about:

fn main() {
    let lines = vec![1,2,3,4,5,6];
    let mut records = std::collections::HashMap::new();

    for i in (0..lines.len()).step_by(2) {
        // make sure the `i+1` is existed
        println!("{}{}", lines[i], lines[i + 1]);
        records.insert(lines[i], lines[i + 1]);
    }
}

Upvotes: 0

Related Questions