How to return an object like TH1F*[][]?

Hi everyone,

Here I have a question more related to c++ than ROOT itself I would say, but I spent hours online look for an answer to this but without any success yet. So I hope you can help me to find my way :slight_smile:

Well, the idea is : I would like to create a function that returns an object like TH1F*[2][3]. Here is what I currently have :slight_smile:

**TH1F** ArrayManager::myHisto()**
**{**
**	TH1F *histo[2][3];**
**	**
**	//Initialization**
**	for(Int_t i=0; i < 2; i++)**
**	{**
**		for(Int_t j=0; j < 3; j++)**
**		{	**
**		histo[i][j] = new TH1F("","",8192,0,8192);**
**		}**
**	}**

**	//Initialize content of every TH1F to 0**
**	for(Int_t i = 0; i < 2 ; i++)**
**	{**
**		for(Int_t j = 0; j < 3 ; j++)**
**		{	**
**			for(Int_t k=1; k < 8192; ++k) **
**			{**
**			histo[i][j]->SetBinContent(k,0);**
**			}**
**		}	**
**		**
**	}**
**	return histo;**
**}**

The compilation fails and I am not surprised since TH1F [2][3] is not TH1F*.
But I also tried to change the function return into :
TH1F ArrayManager::myHisto()[2][3]*
and it still does not want to compile. So I tried different things to return my TH1F *[2][3] but nothing successful yet. Of course you would have noticed that my understanding of pointer and arrays is limited but I couldn’t find any answer online to this problem yet, this is why I am asking for your help.

Do you have any ideas ?

Thanks a lot !

Quentin

Well sorry, I recopy the code correctly :

TH1F** ArrayManager::myHisto()
{
	TH1F *histo[2][3];

	//Initialization
	for(Int_t i=0; i < 2; i++)
	{
		for(Int_t j=0; j < 3; j++)
		{	
		histo[i][j] = new TH1F("","",8192,0,8192);
		}
	}
	//Initialize content of every TH1F to 0
	for(Int_t i = 0; i < 2 ; i++)
	{
		for(Int_t j = 0; j < 3 ; j++)
		{	
			for(Int_t k=1; k < 8192; ++k) 
			{
			histo[i][j]->SetBinContent(k,0);
			}
		}	
	}
	return histo;
}

C++ function can not return arrays (they could return a pointer to an array then the array would need to be allocated on the heap and getting the syntax correct is tricky).

I recommend you either use vector<vector<TH1F*>> or write a small class that contains the array (and then you can return a pointer to that class).

Cheers,
Philippe.

Try with:

std::vector<std::vector<TH1F*> > ArrayManager::myHisto() {
  std::vector<std::vector<TH1F*> > histo(2, std::vector<TH1F*>(3));
  // ...
  return histo;
}

or maybe even better:

std::vector<std::vector<TH1F*> > *ArrayManager::myHisto() {
  std::vector<std::vector<TH1F*> > *histo = 
    new std::vector<std::vector<TH1F*> >(2, std::vector<TH1F*>(3));
  // ...
  return histo;
}

BTW. When you post “source code” or “output” here, do remember to enclose them into two lines which contain just three characters ``` (see how your posts have been edited above).

Hi everyone,

Thank you very much, with your help, I managed to obtain what I wanted. Thanks for the lesson :wink: