C++ - Simple Dynamic 2D array example

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <vector>
#include <iostream>
template <typename T>
class Dynamic2DArray
{
	std::vector<std::vector<T>> m_data;
public:
	Dynamic2DArray(int rowCount, int colCount)
	{
		m_data.resize(rowCount);
		for (auto& item : m_data)
		{
			item.resize(colCount);
		}
	}
	int RowCount() const
	{
		return (int)m_data.size();
	}
	int ColCount() const
	{
		if (m_data.size() > 0)
		{
			return (int)m_data[0].size();
		}
		return 0;
	}
	std::vector<T>& operator[](int rowIdx)
	{
		if (rowIdx >= 0 && rowIdx < (int)m_data.size())
			return m_data[rowIdx];
		throw std::runtime_error("out of index");
	}
	void RemoveLastRow()
	{
		if (m_data.empty() == false)
			m_data.erase(m_data.end() - 1);
	}
	void RemoveLastColumn()
	{
		for (auto& item : m_data)
		{
			if (item.empty() == false)
				item.erase(item.end() - 1);
		}
	}
	void PrintData()
	{
		int colCount = ColCount();
		for (int row = 0; row < (int)m_data.size(); ++row)
		{
			for (int col = 0; col < colCount; ++col)
			{
				std::cout << m_data[row][col] << " ";
			}
			std::cout << std::endl;
		}
	}
};