指向静态数组,但在不使用*的情况下取消引用

Chr*_*rys 1 c++

我有一系列NX对象(例如,下面示例中的维度[NX] [N1] [N2]的静态bool数组).

我想循环这些对象.在每次迭代中,一个名为"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)
      }        
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我想要应用它的对象类型很重,例如容器数组,因此在循环内复制它们是不可接受的.在该应用中通常感兴趣的是最大化性能.

非常感谢帮助!!

编辑:如果A要成为一个标量(即它B[NX]只是),答案将如何受到影响?

fre*_*low 7

您可以在for循环中定义对二维数组的引用:

bool (&A)[N1][N2] = B[x];
Run Code Online (Sandbox Code Playgroud)

现在A[i][j]相当于B[x][i][j].

请注意,您不能移动Afor循环外部的定义,因为引用必须在定义时初始化,并且以后不能反弹.

如果需要A在for循环外定义并在for循环内重新分配,请改用指针:

// outside the for loop
bool (*A)[N2];

// inside the for loop
A = B[x];
Run Code Online (Sandbox Code Playgroud)

这是一个完整的代码示例,可以很好地编译我的编译器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以编写一个别名类模板,该模板适当地重载赋值运算符:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

这适用于数组:

bool B[NX][N1][N2];
alias<bool[N1][N2]> A;
// ...
A.rebind(B[x]);
A[3][5] = true;
Run Code Online (Sandbox Code Playgroud)

和普通的bools:

bool B[NX];
alias<bool> A;
// ...
A.rebind(B[x]);
A = true;
Run Code Online (Sandbox Code Playgroud)