How to fill multiple TTree having same branch

Hi,

I am trying to fill multiple trees having common branches in a single TFile.

But, I am unable to fill trees with data. Below I am adding an example running code.

Please let me know how I can fill them.

Thanks
Ram

void my_tree() {
    TFile *hfile = new TFile("AFile.root","RECREATE","Example");

    // Create trees and store in list
    TTree   *tree = 0;
    auto fList = new TList();
    fList->Clear();
    Int_t Track;
    TString name[8] = { "a", "b", "c", "d", "e", "f", "g", "h" };
    for (Int_t i=0; i<8; i++) {
        tree = new TTree(name[i], "");
        tree->Branch( "Track", &Track, "Track/I");
        fList->Add(tree);
    }

    // Fill trees with data
    for (Int_t i=0; i<3; i++) { // Loop over number of tree
        tree = (TTree*)fList->At(i);
        for (Int_t id=0; id<4; id++) { // Loop over event numbers
            TBranch *br = tree->FindBranch("Track");
            tree->Fill();
        }
    }

    // Write trees to file
    for (Int_t i=0; i<8; i++) {
        tree = (TTree*)fList->At(i);
        // write tree to file
        tree->Write("", TObject::kOverwrite);
        tree->Delete("");   //delete tree from memory
        tree = 0;
    }
}

ROOT Version: ROOT 6.12/06
Platform: Mac OS 10.14.5
Compiler: Not Provided


Hi,
a few things that don’t look ok in your script, in case it helps:

  • you are creating 8 trees but only filling 3 of them (see the end conditions in the for loops)
  • you never change the value of Int_t Track (which is uninitialized): before calling tree->Fill, you should update Track to contain the desired value, e.g.
for (int id=0; id<4; id++) { // Loop over event numbers
    Track = id;
    for (auto obj : *fList) // Loop over trees
        static_cast<TTree*>(obj)->Fill();
}

Also, not real problems, but:

  • the calls to fList->Clear(), tree->FindBranch are useless
  • delete tree would probably be clearer than tree->Delete("")
  • at the end of the file it would be good practice to add a delete hfile
  • it’s probably easier to use a std::vector<TTree*> instead of a TList, because it’s typed, so you can avoid some casts

Hope this helps!
Cheers,
Enrico

P.S.
in case it helps, here are the TTree tutorials

1 Like

Thanks @eguiraud for solving my issue and special thanks for the explanation. This will help me to improve my coding. :slight_smile:

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