繁体   English   中英

如何在 C++ 中的 function 中声明 static 二维数组?

[英]How to declare a static 2D array within a function in C++?

我需要在 function 中声明一个二维数组并重复调用 function 但数组应该在开始时只声明一次。 我怎样才能做到这一点? 我是新手。 提前致谢

Static 函数内部的变量

Static 变量在 function 中使用时仅初始化一次,然后即使通过 function 调用,它们也会保持该值。

这些 static 变量存储在 static 存储区域中,而不是在堆栈中。

考虑以下代码:

#include <iostream>
#include <string>

void counter()
{
    static int count[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    static int index = 0;

    std::cout << count[index / 3][index % 3];
    index++;
}

int main()
{
    for(int i=0; i < 9; i++)
    {
        counter();
    }
}

Output:

123456789
void func1()
{
    static int myArra[10][20];
}

正如拉扎克所说。 这是第一种方式。 第二种方法是使用std::array所以你可以这样完成。

#include <array>
void fun(){
    static std::array<std::array<int, 5>,5> matrix;
}

在 C++ 中,您可以使用std::arraystd::array来创建二维数组:

#include <array>

std::array<std::array<int, 3>, 3> arr = { {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} };

这是一个 3 x 3 2D 数组,每个元素都初始化为 0。访问元素的语法与 C 样式的 2D 数组相同: arr[row][col]

它可以在static中声明为 static,但也可以在 your.cpp 文件顶部的匿名命名空间中声明,如下所示:

namespace
{
   std::array<std::array<int, 3>, 3> arr = { {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} };
}

这通常比 static 变量更好。 该数组仅在主线程启动之前初始化一次,并且只有您的翻译单元(您的.cpp 文件)中的函数可以访问它。

void process(int ele, int index) {
    static std::vector<std::vector<int>> xx_vec = {{1,2,3}, {11,12}, {}};
    // example:
    for (int i = 0; i < xx_vec.size(); i++) {
        // add
        if (index == i) {
            xx_vec[i].push_back(ele);
        }
        // read
        for (int j = 0; j < xx_vec[i].size(); j++) {
            std::cout << "xx_vec" << "place:" << i << "," << j << ":" << xx_vec[i][j] << std::endl;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM