[英]Reference to a static 2D array?
I have some 2D arrays of a static size: 我有一些静态大小的2D数组:
double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];
Later, I want a reference to one of them: 后来,我想要引用其中一个:
double stats[NUM_REPETITIONS][NUM_TRIALS];
if(i == 0) {
stats = quickStats;
}
else if(i == 1) {
stats = mergeStats;
}
else if(i == 2) {
stats = bstStats;
}
However, this does not work. 但是,这不起作用。
What can I do to do what I am trying to do without nested for loops to manually copy each element into the reference array? 如果没有嵌套for循环手动将每个元素复制到引用数组中,我该怎么做呢?
I just need to read from stats, it is to avoid redundant code. 我只需要从统计数据中读取,这是为了避免冗余代码。
Thanks 谢谢
Try this: 尝试这个:
#define NUM_REPETITIONS 10
#define NUM_TRIALS 10
double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];
int main(){
double (* ptr)[NUM_TRIALS] =quickStats;
}
Create a pointer to it like this: 像这样创建一个指向它的指针:
double (*stats)[NUM_REPETITIONS][NUM_TRIALS];
Since your dimensions are known at compile time you can use std::array<>
which is more versatile and readable: 由于您的维度在编译时是已知的,因此您可以使用std::array<>
,它更通用和可读:
std::array<std::array<double, NUM_TRIALS>, NUM_REPETITIONS> stat;
References have to be initialized upon declaration so you cannot assign it later on. 引用必须在声明时初始化,以便您以后不能分配它。 Your best bet is using a pointer or declare the reference inside the if branches. 您最好的选择是使用指针或在if分支内声明引用。
constexpr unsigned int N = 100;
double a[N][N] = {0};
/* Pointer. In your case, N should be NUM_TRAILS here */
double (*a_ptr)[N] = a;
/* Specified Reference Type */
double (&a_ref)[N][N] = a;
/* C++11 Auto Reference */
auto &a_autoref = a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.