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.
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();
}
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.
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.