问题描述
||
我有一系列NX对象(例如,在下面的示例中,尺寸为[NX] [N1] [N2]的静态布尔数组)。
我想遍历这些对象。在每次迭代中,称为“'A \'”的对象将充当系列中相应元素“'B [x] \”的代理。
但是,循环中的代码是遗留代码,因此我们无法真正更改引用“ A”本身的方式
const int NX = ...;
const int N1 = ...;
const int N2 = ...;
bool B[NX][N1][N2];
Code_needed: declare A here (maybe first defining a class template?)
int main(){
for(int x = 0; x < NX; ++x){
Code_needed: make A refer to B[x] here (maybe A = &B[x])
// In the following,\"A[i][j]\" should refer to B[x][i][j]...
A[3][5] = true; // This is legacy code,so we cannot change it
// (e.g.,cannot add a * in front of A)
}
}
请注意,要对其应用此对象的类型很重,例如容器数组,因此不能在循环内复制它们。在此应用中,通常需要使性能最大化。
希望能得到帮助!!
编辑:如果ѭ1是标量(即仅the2ѭ),答案将如何受到影响?
解决方法
您可以在for循环内定义对二维数组的引用:
bool (&A)[N1][N2] = B[x];
现在A[i][j]
等于B[x][i][j]
。
请注意,您不能将ѭ1的定义移到for循环之外,因为在定义引用时必须对其进行初始化,并且它们以后不能反弹。
如果需要在for循环外定义ѭ1并在for循环内重新分配,请改用指针:
// outside the for loop
bool (*A)[N2];
// inside the for loop
A = B[x];
这是一个完整的代码示例,可以在我的编译器上正常编译:
const int NX = 3;
const int N1 = 5;
const int N2 = 7;
bool B[NX][N1][N2];
bool (*A)[N2];
int main()
{
for (int x = 0; x < NX; ++x)
{
A = B[x];
A[3][5] = true;
}
}
您还可以编写一个别名类模板,以适当地重载赋值运算符:
template <typename T>
class alias
{
T* p;
alias(const alias&);
alias& operator=(const alias&);
public:
alias() : p(0) {}
void rebind(T& x)
{
this->p = &x;
}
void operator=(const T& x)
{
*p = x;
}
operator T&()
{
return *p;
}
};
这适用于数组:
bool B[NX][N1][N2];
alias<bool[N1][N2]> A;
// ...
A.rebind(B[x]);
A[3][5] = true;
和普通的bool:
bool B[NX];
alias<bool> A;
// ...
A.rebind(B[x]);
A = true;