Reading a vector from a TBranch

Hello,

I am having trouble with reading vector objects from a TBranch. I have a root file with a TTree inside, and this TTree contains a TBranch made up of vectors. I want to read all the vectors in the branch and write all the floats in each vector to a new vector.

I am following this example:
root.cern.ch/root/html/tutorial … ion.C.html
but I am having trouble at line 118, getting the size of each vector. My code prints the size as 0.

I have also been using this example as a reference:
root.cern.ch/root/html/tutorial … tor.C.html

My code is attached. I get the size at line 35.

Thanks!
tree.C (1.78 KB)

Hi,

here you find an example of how you can read the values contained in a vector of floats which is stored in a tree.
For completeness, you can have a look at how the tree was filled.


void write()
{
   TRandom rndmGen;

   TFile f1("myfile.root", "RECREATE");

   std::vector<float> myVector; myVector.reserve(15);

   // create tree
   TTree t1("myTree", "Tree with vector of floats");
   t1.Branch("myVector", "std::vector<float>", &myVector);

   for (int i=0;i<10;++i) {
      for (int j=0;j<10;++j){
         myVector.push_back(rndmGen.Uniform());
      }
      t1.Fill();
      myVector.resize(0);
   }

   t1.Write();
   f1.Close();

}

void read() {
   TFile f1("myfile.root");
   TTreeReader myReader("myTree",&f1);
   TTreeReaderValue<std::vector<float>> myVectorRV(myReader,"myVector");
   unsigned int evtCounter = 0;
   while (myReader.Next()){
      cout << "Event " << evtCounter++ << endl;
      for (auto&& value : *myVectorRV){
         cout << value << endl;
      }
   }
}

void writeReadTree()
{
   write();
   read();

}

Cheers,
Danilo

1 Like

Hi,

given that this post was liked, I propose an update for @alexis352 .
This tutorial shows how to use TDataFrame to replace TTreeReader, comparing in a very didactic way the traditional approach to reading a TTree, TTreeReader and TDataFrame.

I hope this helps alexis.

Cheers,
D

1 Like

Hi Danilo,

Very useful and very didactic indeed!!
Thank you very much,

Alexis

Hi ,
I am having problem while reading vector objects from a TBranch. I have tried the way suggested by Danilo but the problem is that my branch contains data of type TObjArray. It cannot be accessed by a TTreeReaderValue<vector>.What should i do now.

Hi Kiran,
you could try with a TTreeReaderValue<TObjArray>.

Cheers,
Enrico

Hey eguiraud,
can you send me some program explaining this command as i am beginner in ROOT.

Cheers,
Kiran

Hi eguiraud

Thank you soo much for your suggestion. It worked .

Cheers
Kiran

1 Like

Great,
I’m closing this thread since it’s one year old. Feel free to open a new one should you need further assistance.

Cheers,
Enrico