How to iterate over a vec back and forth based on a position

Hi All

Thanks in advance for your help. I am reading a file. I converted the file lines to Vec and each word to a vec. So it is Vec<Vec<String> and alias as Vec<Line>

In my code I search for a word in this file using position and then read the next couple of lines using iter().next(). Then if I use the position, it is able to search only the next contents and not the previous contents. Is there any better way than creating an iter() again and again?

a X
1 Y
2 Z
c L
4 M
5 N
b A
3 B
4 C
let f = fs::File::open(path).expect("no file found");
let br = BufReader::new(f);
let lines: Vec<Vec<String> = br.lines().filter_map(Result::ok).map(|line| line.split_whitespace().map(|word| word.to_string()).collect());

// Next I am search for a word
let temp = lines.iter();
temp.position(|line| line.contains("a");

let temp = lines.iter();
temp.position(|line| line.contains("b");
let line =;
let v1 = line[0];
let v2 = line[1]
println!("{}", v2);

let temp = lines.iter();
temp.position(|line| line.contains("c"); //Error thrown

First, your example doesn't compile. Even with the missing > added, lines is not a Vec<Vec<String>> but an iterator over it. Please post correct code so that we can easily understand you and it.

That said, creating iterators is cheap. You should keep the Vec around, and make a new iterator whenever you need to.

Thanks! I added the iter() at the last moment before posting and missed errors. I have edited the code

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.