1. GridCell.cpp 파일을 추가한다.
#pragma once
class Cell {
public:
Cell(double value): m_value(value) {}
~Cell(){};
void SetValue(double value);
double GetValue() const;
private:
double m_value;
};
class GridCell
{
public:
GridCell(int rows, int columns): m_rows(rows), m_columns(columns), m_cells(nullptr){
m_rows = rows;
m_columns = columns;
m_cells = new double*[m_rows];
for (int i = 0; i < m_rows; ++i) {
m_cells[i] = new double[m_columns]();
}
}
~GridCell() {
for (int i = 0; i < m_rows; ++i) {
delete[] m_cells[i];
}
delete[] m_cells;
}
void SetCell(int row, int column, double value) {
if (row >= m_rows || column >= m_columns) {
return;
}
m_cells[row][column] = value;
}
double GetCell(int row, int column) const {
if (row >= m_rows || column >= m_columns) {
return 0.0;
}
return m_cells[row][column];
}
void SetSize(int rows, int columns) {
m_rows = rows;
m_columns = columns;
}
private:
int m_rows;
int m_columns;
double** m_cells;
};
2. 메모리 누수 방지를 위해 modern C++ std::vector를 사용합니다.
#pragma once
#include <vector>
class Cell {
public:
Cell(double value) : m_value(value) {}
~Cell() = default;
void SetValue(double value) {
m_value = value;
}
double GetValue() const {
return m_value;
}
private:
double m_value;
};
class GridCell
{
public:
GridCell(int rows, int columns)
: m_rows(rows),
m_columns(columns),
m_cells(rows, std::vector<double>(columns, 0.0))
{
}
~GridCell() = default;
void SetCell(int row, int column, double value) {
if (row < 0 || row >= m_rows ||
column < 0 || column >= m_columns) {
return;
}
m_cells[row][column] = value;
}
double GetCell(int row, int column) const {
if (row < 0 || row >= m_rows ||
column < 0 || column >= m_columns) {
return 0.0;
}
return m_cells[row][column];
}
void SetSize(int rows, int columns) {
m_rows = rows;
m_columns = columns;
m_cells.resize(rows);
for (auto& rowVec : m_cells) {
rowVec.resize(columns, 0.0);
}
}
private:
int m_rows;
int m_columns;
std::vector<std::vector<double>> m_cells;
};
3. 다음도 참고하세요.
int rows = 4;
int columns = 3;
std::vector<std::vector<double>> cells(rows, std::vector<double>(columns, 0.0));
또는
std::vector<std::vector<double>> cells{std::vector<std::vector<double>>(rows, std::vector<double>(columns, 0.0))};
4. 컴파일 시점에 크기를 결정하는 std::array도 참고하세요.
#include <array>
std::array<std::array<double, 3>, 4> cells{};
cells[1][2] = 3.14;
double value = cells[1][2];
for(const auto& row : cells) {
for (double value : row) {
std::cout << value << " ";
}
std::cout << std::endl;
}'C_C++' 카테고리의 다른 글
| C++ : Poco라이브러리로 REST API 서버 만들기(2) (0) | 2026.06.01 |
|---|---|
| C++ : Poco라이브러리로 REST API 서버 만들기(1) (0) | 2026.06.01 |
| C++ : matiaDB ODBC 설치하기 (0) | 2026.05.08 |
| C++ : Visual Studio에서 Static Library 제작 및 사용하기 (0) | 2026.05.02 |
| C++ : mariaDB C/C++ Connector 설치하기 (0) | 2026.04.30 |