动态内存分配:当最右边的维度是可变的时,二维数组的替代方案是什么
Dynamic Memory Allocation: What is the alternative for a two dimensional array when the rightmost dimension is variable?
我正在尝试开发一个类来备份和恢复控制台屏幕缓冲区。这是我正在进行的代码。
class CBuff
{
private:
CONST WCHAR max_unit;
HANDLE hnd;
CHAR_INFO *stor_buff;
COORD s_buff_sz;
COORD d_buff_cod;
SMALL_RECT read_region;
public:
CBuff():max_unit(10)
{}
~CBuff(){}
void Initiate(HANDLE hndl, SHORT buff_x, SHORT buff_y, SHORT buff_width, SHORT buff_height)
{
hnd=hndl;
stor_buff=new CHAR_INFO[buff_width*buff_height]();
s_buff_sz.X=buff_width;
s_buff_sz.Y=buff_height;
d_buff_cod.X=0;
d_buff_cod.Y=0;
read_region.Left=0;
read_region.Top=0;
read_region.Right=buff_width-1;
read_region.Bottom=buff_height-1;
}
int Backup()
{
if(!ReadConsoleOutput(hnd,stor_buff,s_buff_sz,d_buff_cod,&read_region)) return -1;
return 0;
}
int Restore()
{
if(!WriteConsoleOutput(hnd,stor_buff,s_buff_sz,d_buff_cod,&read_region)) return -1;
return 0;
}
int Backup_mp()
{/*incomplete*/}
int Restore_mp()
{/*incomplete*/}
};
它与 Backup() 和 Restore() 配合使用很好。然后我尝试制作另一个版本的备份,Backup_mp(handle, backup_num)
,它将从不同的控制台缓冲区实例创建多个备份。我计划将私有空间中的最后四个变量转换为数组,以便索引值 (backup_num) 可用于不同的备份点。像这样的分配
stor_buff=new CHAR_INFO[index][buff_width*buff_height]();
不工作。
我有什么选择?
另外,我可以使用 CONST WCHAR max_unit
作为像 s_buff_sz[max_unit]
这样的数组的参数吗?
你正在使用C++,所以要利用它:使用 std::vector。
//Declaration of your buffers:
std::vector< std::vector<CHAR_INFO> > store_buffers;
//Append a new buffer entry:
store_buffers.push_back( std::vector<CHAR_INFO>( buff_width * buff_height ) );
// Pass buffer with index index to WinAPI functions:
..., store_buffers[index].data(), s_buff_sz, ...
如果使用 C++11,则可以将 std::array 用于固定大小的维度(而不是可变的 std::vector),但这并不重要。
要在堆中分配二维数组(使用 new
),您需要先分配指针,然后再分配数组。例:
stor_buff = new CHAR_INFO* [buff_height]; // Allocate rows (pointers
for(int index = 0; index < buff_height; ++index)
stor_buff[index] = new CHAR_INFO[buff_width];
并直接使用它们,就好像store_buff
是 2D 数组一样。对于释放,您需要先删除数组(即单个行),然后再删除行指针。
for(int index = 0; index < buff_height; ++index)
delete []stor_buff[index]; // NOTICE the syntax
delete []stor_buff;
或者,您可能有一个一维数组,将其用作 2D。为此,您需要进行(row,col)
计算才能获得所需的元素。
您也可以使用 vector
(或vector
vector
),以获得相同的结果。但我建议你玩原生指针,除非你习惯了指针!
相关文章:
- 在创建动态二维数组时,在A[i*c+j]中使用c有什么用,即c代表什么
- 如何为映射和priority_queue编写比较器,其中元素是二维数组
- 当 p 是二维数组时,为什么 p、*p 和*p 具有相同的值?
- 我们可以在 C++ 编程中使用的二维数组的最大大小是多少?
- 在 c 和 c++ 中,二维数组的元素是什么类型?
- 这是用于对二维数组进行排序的最佳方法
- 遍历二维数组的时间复杂度是多少
- 存储二维数组指针的方法是什么
- 打印空白,而不是二维数组c++中的整数
- 是一个二维数组的名称,它在C++中的第一个元素的地址
- 如果两个维度在编译时都是未知的,如何传递二维数组
- 什么是快速矩阵或二维数组,用于在C++中存储邻接矩阵
- 是在内存中连续设置的二维数组,类似于模拟二维数组的一维数组
- 为什么二维数组中的Range是这样写的
- 当您有一个二维数组(C++)时调用析构函数的正确方法是什么?
- 为什么使用一维数组而不是二维数组?
- 关于C++中的二维数组,我的解决方案有什么问题
- 为什么我可以声明一个二维数组与两个维度大小的变量,但不是新的
- 双指针和二维数组之间的关系是什么?
- 动态内存分配:当最右边的维度是可变的时,二维数组的替代方案是什么