Write each element of std::vector as individual branch element of same name

I am trying to compute a function of branch “b1” from a root file with N elements say. The idea is to write the values of this function as branch in a new root tree so that I can use it as a friend.

For each element of branch I compute the function, and save it as element of a std::vector of size N.

When I write this vector into a new root file, it just gets written as one entry because its just one single std::vector object I guess. This creates a problem for adding as friend of original tree because the entry count don’t match with the branch “b” from original tree.

Is there a way to write the elements of std vector such that they are written as individual elements in the new tree? Basically I would like each element of the vector to be a leaf element.

How are you saving it to the new root file? If you are using a tree (since you say you want to use tree friends), just don’t declare the branch as a vector, but as a single value (int/double), and fill it once per each vector element (the vector should have the same size as entries in the original tree, if it’s going to be a friend) e.g.

double newval=0;
TTree *Tnew = new TTree("Tnew","new");
Tnew->Branch("v",&newval,"v/D");
// and then loop over the vector elements (e.g. vec[i]) and fill Tnew each time
for (int i=0; i<vec.size();++i) {
  newval = vec[i];
  Tnew->Fill();
}
//...

Thank you very much. This was exactly what I was looking for. I had tried something similar myself but I had the line equivalent to Tnew->Branch("v",&newval,"v/D") inside the loop which took extremely long time to save the tree and took up significantly more (1000x) space.

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