如何在C++函数中声明静态 2D 数组?

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

本文关键字:静态 2D 数组 声明 C++ 函数      更新时间:2023-10-16

我需要在函数中声明一个 2D 数组并重复调用该函数,但数组应该只在开头声明一次。 我该怎么做?我是新手。 提前致谢

函数中的静态变量

在函数内部使用的静态变量只初始化一次,然后它们甚至通过函数调用也保持在那里的值。

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

请考虑以下代码:

#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();
}
}

输出:

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::arrays 的std::array来创建 2D 数组:

#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,但也可以在.cpp文件顶部的匿名命名空间中声明,如下所示:

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

这通常是比静态变量更好的做法。数组仅在主线程启动之前初始化一次,并且只有翻译单元(.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;
}
}
}