Adding a Pre-existing TBranch to TTree

ROOT Version: 5
Platform: Scientific Linux 6.10
Compiler: g++ 4.4.7

Hi everyone, I am struggling with writing TBranch objects out of a vector into a new tree. More specifically, I am unsure about how one initializes the address of a new TBranch so that when I fill the TTree, a copy of a pre-existing TBranch is written to it. Here is a minimal code to show the problem:

#include <iostream>
#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>
#include <TKey.h>

using namespace std;

int main(){

  int i = 0;
  vector<TBranch*> Detectors;
  TFile* data = TFile::Open("Data.root");
  TKey *key = 0;
  TTree* event = 0;
  TBranch* detector = 0;
  TObjArray* branch_list = 0; 
  	TIter next_event(data->GetListOfKeys()); 
		while((key = (TKey*)next_event())){
		  if(strcmp(key->GetClassName(), "TTree")){
		  event = (TTree*)data->Get(key->GetName()); 
		  branch_list = event->GetListOfBranches();
		  for(i = 0; i < branch_list->GetEntries(); i++){
		    detector = (TBranch*)branch_list->At(i); 
  else{cout << "ERROR: File failed to open." << endl;}
  TFile* rootout = TFile::Open("Test.root", "recreate");
  for(i = 0; i < Detectors.size(); i++){
    TTree* out_tree;

    //Don't know how to initialize the branch to copy the Detectors[i] branch and associate it with the TTree
    TBranch* out_branch = out_tree->Branch(Detectors[i]->GetName(), &Detectors[i], "data/I"); 
    out_branch = Detectors[i];

  return 0;

Try with the TTree::CloneTree method:

grep -r CloneTree ${ROOTSYS}/t[eu]*
1 Like

I was hoping to add a branch from the vector rather than from the original tree. If I understand correctly, CloneTree method will copy from the original TTree instead.

Can you clarify your goal? (i.e. where is the data for the ‘vector’ coming from compared to CloneTree)?

Thanks for further interest in the topic. I re-wrote my code and used CloneTree() method and forgot to mark the thread solved. I shall do that now.

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