Accessing particular entries of TTreeReaderValue

Hello *,
I am trying to use TTreeReaderValues like below

TFile *myFile = TFile::Open("hello.root");
TTreeReader myReader("MYTree", myFile);
TTreeReaderValue<Track> myTrack(myReader, "Track");

if i access the entries like

while (myReader.Next()) {

then its working fine.

but if i want to access only a specific entry say entry no. 10.
then also do i have to traverse using Next() function ? or is there
any way to access the required entry directly,
may be something like



I think you are missing the type of the variable. Try:

TFile *myFile = TFile::Open("hello.root");
TTreeReader myReader("MYTree", myFile);
TTreeReaderValue<Float_t> myTrack(myReader, "Track");

while (myReader.Next()) {
    std::cout << *myTrack << "\n";

Or similar (this is for the case where your branch is a float).

This is also visible in the examples given in the documentation.

Hi Graipher ,
Ya that the typo,
In my case it is my class call Track
TTreeReaderValue < Track > myTrack(myReader, “Track”);

After that the question remain same, you are also accessing different entries
by traversing one by one using Next()

But is there any way to access directly a particular entry like entry num 5

I think in that case you just want to use the normal approach. I think TTreeReader is better if you really want to run over all entries.

TFile *myFile = TFile::Open("hello.root");
TTree* tree = (TTree*) myFile->Get("MYTree");

// Setup branch addresses
Track myTrack;
tree->SetBranchAddress("Track", &myTrack);

// Get entry number 5
tree->GetEntry(4);  // indices start at 0

If somewhere else you need to loop over all entries, you can do that, too:

// Loop over all entries
Long64_t nentries = tree->GetEntries();
for(Long64_t i=0; i < nentries; i++) {

I’d suggest sticking with TTreeReader actually: it has a SetEntry method:

TFile *myFile = TFile::Open("hello.root");
TTreeReader myReader("MYTree", myFile);
TTreeReaderValue myTrack(myReader, "Track");
myTrack.Print(); // prints 11th entry
1 Like

…and since we are here, here is how you do it with TDataFrame (complete working code) :slightly_smiling_face:

#include "ROOT/TDataFrame.hxx"
ROOT::Experimental::TDataFrame d("MYTree", "hello.root");
auto vecTrack = d.Range(10,11).Take<Track>("Track");
// vecTrack has size 1 and vecTrack[0] is your 10th entry :)
1 Like

As enrico says.
A thing I’d like to note is that the number of lines needed to get out your track from the entire dataset with TDataFrame is 2 against the 5 of the other two cases.


Thanks everybody,
That worked.
I will mark it as SOLVED.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.