一维数组模拟二维数组 C++类实现 一诚
作者:
AC_any
,
2021-06-03 22:47:47
,
所有人可见
,
阅读 421
#pragma once
#include<iostream>
#include<cstdint>
#include<cstdio>
template <typename T = char>
class Array2D
{
public:
/**
* @param row
* @param col
*/
Array2D(int row, int col) : NR(row), NC(col)
{
m_data = new T[row * col];
}
~Array2D() { delete[] m_data; }
const uint32_t row() { return NR; }
const uint32_t col() { return NC; }
/**
* 取数据arr[row][col]
*/
T& at(int row, int col)
{
return m_data[row * NC + col];
}
inline T& operator()(int row, int col)
{
return this->m_data[row * NC + col];
}
/**
* 取第row行数据arr[row]
*/
const T* at(int row)
{
return (m_data + row * NC);
}
inline const T* operator[](int row) const
{
return &(m_data[row * NC]);
}
/**
* @param value
*/
void clear(int value)
{
for (uint32_t i = 0; i < NC * NR; i++)
m_data[i] = value;
}
private:
uint32_t NR;
uint32_t NC;
T* m_data = nullptr;
};
int testForArray2D()
{
Array2D<char> arr(3, 4);
arr.clear('#');
std::cout << arr(1, 3) << std::endl;
const char* now = arr[1];
arr.clear('G');
for (int i = 0; i < 4 && now; i++)
{
std::cout << *(now + i) << " ";
}
std::cout << std::endl;
return 0;
}