Is there a tidier way to merge a std::vector of TH1F?

ROOT Version: 6.18/04
Platform: Ubuntu 20.04.2

Hello ROOT forum users,

Currently when I performing multiprocessing, I receieve a TH1F back from each of my processes, which are returned in a std::vector of TH1Fs. I then have to merge those histograms. My process, as you will see in the code snippet below, involves what feels like an unnecessarily complicated process to me, of cloning a histogram, dynamically allocating a list, taking my objects from the vector and putting them into a list, and then using the cloned histogram to merge the list. My impression after writing this code was “there has to be a better way of doing this”. My question to the ROOT community is: is there is a shorter or “proper” way of merging a std::vector of histograms that I have missed?

TH1F multiprocess_analysis()
   //Retrieve a vector of TH1Fs
   std::vector<TH1F> process_output = function_returning_TH1F_vector();

   //1.) make a clone of the first TH1F in the vector and point to it
   TH1F* h = (TH1F*)process_output[0].Clone();

   //2.) create a list
   TList *list = new TList;

   //3.) loop through the TH1Fs in the vector and add them to the list
   for (TObject & hist : process_output)
   //4.) use the previously cloned TH1F to merge the list

   //5.) Take the TH1F pointer to the merged histogram and store 
   //the value it points to in stack memory
   TH1F h2 = *h;

   //6.) Delete the list so I don't leak memory
   delete list; 

   //7.) Return the merged TH1F
   return h2;

Thank you for your help,

Joseph DeCunha

The TH1::Merge method expects some object that inherits from the TCollection class, so maybe your “multiprocessing” could return one (instead of a “std::vector”).

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