Adding histograms

Hi,

I am trying to read N files and I want to add up one histo which is in each file and write out the final histo to a new file. Sounds simple … I do not understand why it crashes when the input files are closed. I thought cloning the histo or deep copy should prevent that but closing the file still seems to make the cloned histo invalid, even if I give another name.

(I know I could use hadd to just add histo files but it is not an option here due to other requirements)
Thanks
Andi

TH1F* electronPreTag(0);
for (std::vector< TString >::iterator itr = fileList.begin() ; itr != fileList.end() ; itr++)
{
TFile f(itr, “READ”);
TH1F
h = (TH1F*)f->Get(“D3PDBookkeeping/ElectronPreTag”);
std::cout << h->GetBinContent(1) << std::endl;
if (electronPreTag==0) electronPreTag = new TH1F(*h); // ->Clone(); // ->Clone(“newname”);
else electronPreTag->Add(h); // CRASH
f.Close();
}

std::cout << electronPreTag->GetBinContent(1) << std::endl;

if (electronPreTag==0) electronPreTag = new TH1F(*h); // ->Clone(); // ->Clone("newname"); here the output histogram attach itself to the current directory and thus will be deleted when it is closed.
Useif (electronPreTag==0) electronPreTag = h; h->SetDirectory(0); // or better yet SetDirectory(output_directory);

Cheers,
Philippe.

Hi Philippe,

thanks this works. I would never have figured that out :confused:

Cheers
Andi