Reset the reader from TTreeReader

Hi, so I am reading a the branches of a tree in c++ with:

TTreeReaderValue<float> mcWeight(reader, "mcWeight");

and i am looping through the events in the tree with:

while( reader.Next()) {}

But i need to make a loop a trough the tree with something like:

for(int i=0; i < 3000 ; i++) {
   while( reader.Next()) {} 
}

but when I do it, the code just “get” into the while() for the first interaction of I, after that it just passes through. I guess I need to restart the reader right? How can I do that?

Best Regards,
Caio.

You could try something like this:

reader.Restart(); // start from the first entry
int i = 0;
while (reader.Next()) {
  if (++i > 3000) break; // exit "while" after (at most) the first 3000 entries
  // ...
}

Unless you really want:

for (int i = 0; i < 3000; i++) {
  reader.Restart(); // always start from the first entry
  while(reader.Next()) { // loop over all available entries
    // ...
  }
}
1 Like

Can you elaborate on why? while (reader.Next()) already loops over the full tree, why do you need to do it 3k times? There might be a better way to do what you want to do.

Cheers,
Enrico

1 Like

Thanks, @Wile_E_Coyote, and @eguiraud for the tips and solution! Yes indeed, there are better ways to handle this, as the one Wile suggested. But then I will need to create a bunch of histograms for each mass interval I need to look to, so the reader.Restart() is the lazy way I will use for exploratory purposes.