c++ - 内存地址的变量名递增
问题描述
这可能是一个非常简单的答案,我不确定。我必须给出一个变量的地址才能读入根目录中的一些值。我需要不同的变量名,因为我想稍后比较它们。有没有一种方法可以一步将它们读入正确命名的变量(双精度类型),这些变量被递增命名(Detector_P0
,Detector_P1
等)。这就是我到目前为止所拥有的:(我让它为 工作branchName
,但不是&variableName
在工作SetBranchAddress()
)。任何建议将不胜感激!!!
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,&???);
}
解决方案
您最好的选择是使用数组或类似对象的数组,例如std::vector
or std::array
。
如果数组的大小是已知的编译时间,最好使用std::array<double, SIZE>
.
如果仅在运行时知道数组的大小,请使用std::vector<double>
.
使用示例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]));
}
是的,每个 Detector_P$ 变量大约有 5000 个与每个相关的数字。当我运行这个文件时,我马上就知道需要多少个 Detector_P 变量。所以我想以某种方式为每个或在列表中创建一个数组,我可以增加一些东西来比较某些索引
似乎您需要 astd::map<std::string, std::vector<double>>
来保存数据。
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]);
}
double
这允许您读取与检测器对应的尽可能多或尽可能少的 s 并将它们存储在allDetectorData[branchVarName]
.
然而,我最关心的是这对你有多大意义。在尝试在应用程序中使用它们之前,花时间真正了解标准库中的容器类模板是值得的。我建议从一本好的教科书中了解它们。
推荐阅读
- mysql - 将数据从本地 MySQL 服务器传输到远程 SQL 服务器?
- c++ - 如何暂停循环几秒钟?
- javascript - jQuery slideToggle() 方法
- python - 使用重定向时python3中的UnicodeEncodeError
- javascript - 如何使用谷歌脚本从谷歌表格中提取特定列?
- javascript - Is running out of memory in Node an indication of a memory leak?
- mongodb - $map 最多三个嵌套数组 mongodb 聚合
- javascript - Timeline with load more function
- javascript - 将具有父 ID 的对象数组转换为嵌套树结构
- resize - Unity Prevent game objects from resizing when resolution changes