# Creating histograms through a function

Hi root community,

In my code I want to create different histograms like such:

``````TH1D* D0_x = new TH1D("D0_x_vertex", "D_{0} production vertex x", 10000, -1, 1);
TH1D* D0_y = new TH1D("D0_y_vertex", "D_{0} production vertex y", 10000, -1, 1);
TH1D* D0_z = new TH1D("D0_z_vertex", "D_{0} production vertex z", 10000, -1, 1);
TH2D* D0_map = new TH2D("D0_production_map","Map of the D_{0} production vertices",10000, 0, 1., 10000, 0, 1.);
TH1D* D0_daughters_x = new TH1D("x_vertex_D0_daughters", "D_{0} production vertex x", 10000, -1, 1);
TH1D* D0_daughters_y = new TH1D("y_vertex_D0_daughters", "D_{0} production vertex y", 10000, -1, 1);
TH1D* D0_daughters_z = new TH1D("z_vertex_D0_daughters", "D_{0} production vertex z", 10000, -1, 1);
TH2D* D0_daughters_map = new TH2D("D0_daughter_Production_map","Map of the D_{0} daughter production vertices",10000, 0, 1., 10000, 0, 1.);
``````

I want to create similar histograms for the D*, D1 and D2. Of course I could just copy all of this and change the D0 parts in all of the histograms, but this doesnâ€™t seem like the neatest way to do this. I would like to create a function in which I can enter which particle I want to generate histograms for, with as a result that the names of the created histograms are changed accordingly inside this function. Can this be done, or does c++ not allow for this?

ROOT Version: 6.22
Platform: MacOS
Compiler: gcc

Hi,

Yes this can be done in C++, you create a generic function and if only the name changes you can create different strings in C++. For example you can set a generic names following using ROOT TString:

``````TString particleName = "D0";
TString hName = TString::Format("%s_x_vertex",particleName.Data());
TString hTitle = TString::Format("%s production vertex",particleName.Data());
TH1D * hx = new TH1D(hName, hTitle, 10000, -1, 1);
``````

and you could return your histogram from the function in a `std::vector<TH1*>` or a ROOT `TList` . The histogram are anyway added to the current directory, `gDirectory` and you can always retrieve using their name

Lorenzo

Thanks, this is exactly what I needed!