Filling a TH2D in map(pair<int, int>,TH2D)

You are using a const_iterator but Fill obviously isn’t const. That is also what your error message says: no known conversion from 'const TH2D' to 'TH2'.

Solutions:
a) (the obvious one) use a non-const iterator
b) (what I would suggest) change your map. Make the value a TH2* instead of a TH2D, i.e. std::map<pair<int, int>, TH2*> myMap; You can then remove the variable t_vs_t and your loop can look like this:

for (int i = 1; i<=47; i=i+2) {
    myMap[std::make_pair(i,i+1)] = new TH2D(Form("t%d_vs_t%d",i,i+1), Form("t%d_vs_t%d",i,i+1),
                                            ntdcbins, tdcmin, tdcmax,
                                            ntdcbins, tdcmin, tdcmax);
}

This will also get rid of the useless copy of the histogram you’re making in the myMap[...] = *t_vs_t line.

And finally the histograms in this map can also be filled using the map’s const_iterator because it will just make the pointer const, i.e. accessing it->second is accessing a TH2* const, not a const TH2*.

///

Final comment: I find it a bit strange that you have a pair as map key. At least in this code the pair is always (i,i+1), thus it would be sufficient to use i as key.

Edit: @ksmith: you obviously had the same idea and were a few seconds faster :slight_smile:

1 Like