简体   繁体   中英

Increment by variable names for a memory address

This may be a very simple answer, I am not sure. I have to give the address of a variable to read in some values in root. I need different variable names because I want to compare them later. Is there a way to all in one step read them into correctly named variables (typed double) that are incrementally named ( Detector_P0 , Detector_P1 , etc.). This is what I have so far: (I have it working for the branchName , but not the &variableName in SetBranchAddress() ). Any advice would be greatly appreciated!!!

for (int i = 0; i < nb_det; i++) {

std::string branchVarName = "Detector_P" + std::string(to_string(i));

const char * branchVarNameC;

 branchVarNameC = branchVarName.c_str();

All->SetBranchAddress(branchVarNameC,&???);

}

Your best option is to use an array or array like object, such as std::vector or std::array .

If the size of the array is known compile time, prefer to use std::array<double, SIZE> .
If the size of the array is known only at run time, use std::vector<double> .

Example using std::vector :

std::vector<double> data(nb_det);
for (int i = 0; i < nb_det; i++)
{
   std::string branchVarName = "Detector_P" + std::string(to_string(i));
   const char * branchVarNameC = branchVarName.c_str();
   All->SetBranchAddress(branchVarNameC, &(data[i]));
}

Yes, with each Detector_P$ variable there are approximately like 5000 numbers associated with each. When I run this file I do know right away how many there Detector_P variables there will need to be. So I would like to somehow create an array for each or at the very list something I can increment over to compare certain indices

It seems like you need a std::map<std::string, std::vector<double>> to hold the data.

std::map<std::string, std::vector<double>> allDetectorData;
for (int i = 0; i < nb_det; i++)
{
   std::string branchVarName = "Detector_P" + std::string(to_string(i));
   const char * branchVarNameC = branchVarName.c_str();
   All->SetBranchAddress(branchVarNameC, allDetectorData[branchVarName]);
}

That allows you to read as many or as few double s corresponding to a detector and store them in allDetectorData[branchVarName] .

However, what concerns me most is how much of this makes sense to you. It will be worth your while to spend time understanding the container class templates in the standard library really well before venturing into using them in your application. I recommend learning about them from a good textbook .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM