004
05.08.2007, 12:10 Uhr
xXx
Devil
|
Hmm ... ok ... nen paar Sachen auch direkt verändert:
C++: |
#include <algorithm> #include <stdexcept>
namespace math { template <typename T> class matrix { public: matrix(std::size_t row = 1, std::size_t col = 1) : m_row(row), m_col(col) { m_data = new T*[row]; for (std::size_t cur = 0; cur < row; ++cur) m_data[cur] = new T[col]; }
~matrix() { for (std::size_t cur = 0; cur < m_row; ++cur) delete [] m_data[cur]; delete [] m_data; }
T& operator ()(std::size_t row, std::size_t col) { return at(row, col); } T const& operator () (std::size_t row, std::size_t col) const { return at(row, col); } T* operator [](std::size_t row) { return m_data[row]; }
public: T& at(std::size_t row, std::size_t col) { if (row >= m_row || col >= m_col) throw std::out_of_range("col and/or row"); return m_data[row][col]; } T const& at(std::size_t row, std::size_t col) const { if (row >= m_row || col >= m_col) throw std::out_of_range("col and/or row"); return m_data[row][col]; } T const & min() const { T const & min; for (std::size_t row = 0; row < m_row; ++row) for (std::size_t col = 0; col < m_col; ++col) min = std::min(m_data[row][col], min); return min; } T const & max() const { T const & max; for (std::size_t row = 0; row < m_row; ++row) for (std::size_t col = 0; col < m_col; ++col) max = std::max(m_data[row][col], max); return max; } std::size_t size() const { return (m_row * m_col); } void resize(std::size_t row, std::size_t col) { T** tmp_data = new T*[row]; for (std::size_t cur_row = 0; cur_row < row; ++cur_row) { tmp_data[cur_row] = new T[col]; for (std::size_t cur_col = 0; cur_col < col; ++cur_col) if (cur_col < m_col && m_row > cur_row) tmp_data[cur_row][cur_col] = m_data[cur_row][cur_col]; } for (std::size_t cur = 0; cur < m_row; ++cur) delete [] m_data[cur]; delete [] m_data; m_data = tmp_data; m_row = row; m_col = col; }
void sort() { for (std::size_t cur_row = 0; cur_row < m_row; ++cur_row) std::sort<T>(m_data[cur_row], m_data[cur_row] + m_col); }
private: T** m_data; std::size_t m_row; std::size_t m_col; }; };
|
C++: |
#include <iostream> #include "math.h"
template<typename T> void show(const math::matrix<T>& mat, std::size_t row, std::size_t col) { std::cout << mat(row, col) << std::endl; }
int main() { math::matrix<int> mat(4, 4); mat.at(1, 1) = mat.size(); mat.resize(6,6); try { mat(6, 6) = 1; } catch(std::out_of_range& ex) { std::cout << ex.what() << std::endl; } mat(5, 1) = 1; show<int>(mat, 5, 1); ++mat[5][1]; show<int>(mat, 5, 1); }
|
... |