C++ – Simple Dynamic 2D array example

#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;
		}
	}
};
Advertisements
This entry was posted in C++, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s