Weird THStack iterator error


ROOT Version: 6.16/00
Platform: Ubuntu 18.04.1
Compiler: g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0


A THStack is filled with TH1F. The stack of histograms is obtained using THStack::GetStack. (This is supposed to build the stack if it wasn’t already built). begin and end iterators of the stack are obtained. These are found to be equal!! How come?? GetNEntries on stack returns the non zero no. of histograms added.

(In the following sop is just like cout)
Code:


#include <THStack.h>
#include <iostream>

using std::cout;
using std::endl;
using std::cerr;

class sop{

    template<class T>
    friend sop& operator<<(sop & out,T obj)
    {

        std::cout<<obj<<std::endl;

        return out;
    }

};

void rough2()
{
sop sop;
    int n=5;
    THStack *stk=new THStack();
    for(int i=0;i<n;i++)
    {
        TH1F * hist=new TH1F("","",50,-3,3);
        hist->FillRandom("gaus",1000);
        stk->Add(hist);
    }

    auto s=stk->GetStack();
    sop<<s->GetEntries();
    auto begin=stk->begin();
    auto end=stk->end();
    int count=0;
    sop<<(begin==end?"true":"false");

    for(auto iter=begin;iter!=end;++iter)//doesn't execute even once
    {
        ++count;
        sop<<count;
        if(count>n+3)
            break;
    }



}

PS:
Ultimate goal is: given a THStack, build a Tlegend from it. For this I wanted to iterate over the underlying histograms.

#include <THStack.h>
#include <iostream>

using std::cout;
using std::endl;
using std::cerr;


void rough2()
{
    int n=5;
    THStack *stk=new THStack();
    for (int i=0;i<n;i++) {
        TH1F * hist=new TH1F(Form("h%d",i),"",50,-3,3);
        hist->FillRandom("gaus",1000);
        stk->Add(hist);
    }

    auto s = stk->GetHists();

   TIter next(s);
   TH1F *h;
   int count=0;
   while ((h=(TH1F*)next())) {
      ++count;
      cout << count << " " << h->GetName() << endl;
   }
}
1 Like

Thanks a ton for the help. But why does begin==end give true?

When you need to loop over the histograms in a TStack you should use the list of histogram returned by GetHists()

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