Creating histograms within a loop

Hi all,
I’m trying to create a bunch of histograms whose names vary only slightly. They’re something like
histo1_neutron
histo2_neutron

histoN_neutron
histo1_gamma
histo2_gamma

histoN_gamma

Is there a way I can create these histograms (as pointers) in a for loop by looping over both the number (1,…,N) as well as the particles (neutron, gamma, …) e.g. by creating an array of the particles then looping over the entries in the array as well as the number 1 to N?

Thanks!

Hi,

certainly yes. This should get you started:

std::vector<TH1F*> myHistos; // you need to free this memory later
for (auto i : {1,2,3,4}) {
   for (auto part_name : {"neutron", "gamma", "whatever"}) {
      myHistos.emplace_back(new TH1F(Form("%s_%d", part_name, i),"yourtitle",64, -4, 4)); // binning made up
   }
}

I hope this help.
P

1 Like

Thanks! How (and when) do i clear the memory?

Hi,

it really depends on you and when you need to free it. If you prefer an automatic management, i.e. by the cpp runtime, just use a vector<unique_ptr> :slight_smile:

Cheers,
P

1 Like

Thank you so much for your help!

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