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

标签 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)
      }        
    }

请注意,我要应用它的对象类型很重,例如容器数组,因此在循环内复制它们是 Not Acceptable 。最大化性能通常是此应用程序的兴趣点。

非常感谢您的帮助!!

编辑:如果 A 是一个标量(即它只是 B[NX]),答案会受到怎样的影响?

最佳答案

你可以在for循环中定义一个二维数组的引用:

bool (&A)[N1][N2] = B[x];

现在 A[i][j] 等同于 B[x][i][j]

请注意,您不能将 A 的定义移到 for 循环之外,因为引用必须在定义时进行初始化,并且以后不能重新绑定(bind)。

如果您需要在 for 循环外定义 A 并在 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;

关于c++ - 指向静态数组,但在不使用 * 的情况下取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6362719/

相关文章:

c++ - STL 与 struct 的速度问题

C++ 回调数组

c++ - 具有零个或多个附加参数的可变参数宏

c++ - 基于时间的旋转

c++ - Node Js 与 C++ 简单数学性能对比

c++ - Windows CE下单行EDIT控件按ENTER键时如何关闭提示音?

c++ - 从键盘读取 IP 地址 ipv4 并使用 scanf 函数检查其是否有效

c++ - 我写了这个程序用于中缀到后缀的转换

c++ - 在 Qt 中的窗体之间传输数据

c++ - Boost::Property_Tree 设置