如何在C++函数中声明静态 2D 数组?
How to declare a static 2D array within a function in C++?
我需要在函数中声明一个 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::array
s 的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;
}
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++函数中声明静态 2D 数组?
- 静态2D数组,添加元素
- 如何在C++中静态铸造 2D 矢量大小()(size_t 到 int)
- 静态2D阵列初始化
- 使用MPI和C 发送静态内存2D数组
- CUDA:是将 M[][] 用于 2D 静态数组还是将它们展平为 M[] 更好
- 如何在c++中静态初始化2d数组的数组
- 用静态2d数组定义类的方便方法是什么(并且2d数组的大小只有在编译时才知道)
- 具有大的2d数组:静态int与int
- 在静态2D数组的声明处初始化为零
- 将静态 2D 数组的行分配给另一行