请原谅我的无知,但我是 C++ 和 ROOT 的新手,我不知道我做错了什么。
我要做的是编写一个函数,该函数返回直方图中 n 峰值的 bin 位置。以下是我的代码:
#include <iostream>
#include <algorithm>
#include <iterator>
#include "TROOT.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TF1.h"
using namespace std;
int *peak_counter1d(TH1F *histogram,int peak_num,int threshold = 5,int display = 0){
if(display == 1){
TCanvas *look = new TCanvas("look","look",500,400);
histogram->Draw();
}
int total_bins = histogram->GetNBinsX();
double peak_bins[peak_num];
peak_bins[0] = histogram->GetMaximumBin();
int counter = 1;
int *check_array; // to put previously found peak bins
while(counter < peak_num){
double peak = threshold;
double peak_loc = -500;
check_array = new int[counter];
for(int i=0; i<counter; i++){
check_array[i] = peak_bins[i]; // fills the array with previously found peak bins
}
for(int i=0; i<total_bins; i++){
if(peak < histogram->GetBinContent(i)){
bool exists = find(begin(check_array),end(checkarray),i); // makes sure this is a peak we haven't already found
if(!exists){
peak = histogram->GetBinContent(i);
peak_loc = i;
}
}
}
peak_bins[counter] = peak_loc;
counter ++;
}
delete[] check_array;
return peak_bins;
}
void testing(){
gROOT->Reset();
TH1F *histo = new TH1F("histo","try",100,0,10);
TF1 *f1 = new TF1("f1","exp(-x/10)*sin(x)*sin(x)",0,10);
double val;
for(int i=0; i<100; i++){
val = f1->Eval(i/10.0);
//cout << i << "\t" << i/100.0 << "\t" << val << endl;
histo->SetBinContent(i,val);
}
int *peak_bins;
peak_bins = peak_counter1d(histo,3,5,1);
for(int i=0; i<3; i++){
cout << i << "\t" << *(peak_bins+i) << endl;
}
}
当我在 ROOT 中执行此代码时,我得到以下信息:
root [] .x testing.cpp
Error: Can't call TH1F::GetNBinsX() in current scope testing.cpp:15:
Possible candidates are...
(in TH1F)
(in TH1)
*** Interpreter error recovered ***
我认为这是访问函数内部对象方法的问题,因为当我在 testing() 函数中调用 histo->GetNBinsX() 方法时,我没有遇到任何问题。不过我不知道。
谢谢,如果我正在做其他灾难性的可怕编码实践,请告诉我。