| Lesson 15 | Dynamic Multidimensional Arrays |
| Objective | Implement a safe, modern C++ find_max() for 2-D data and verify with simple tests. |
Main point: represent a 2-D matrix safely and write a clear, correct, and testable find_max() that works for any dimensions.
This version stores elements in a single contiguous buffer (row-major). It’s compact, fast to iterate, and easy to reason about.
#include <vector>
#include <cstddef> // size_t
#include <stdexcept> // std::invalid_argument, std::out_of_range
struct Matrix {
std::size_t rows{};
std::size_t cols{};
std::vector<double> data; // rows * cols, row-major
Matrix(std::size_t r, std::size_t c, double init = 0.0)
: rows(r), cols(c), data(r * c, init) {
if (r == 0 || c == 0) throw std::invalid_argument("Matrix dimensions must be > 0");
}
double& at(std::size_t r, std::size_t c) {
if (r >= rows || c >= cols) throw std::out_of_range("Matrix index");
return data[r * cols + c];
}
double at(std::size_t r, std::size_t c) const {
if (r >= rows || c >= cols) throw std::out_of_range("Matrix index");
return data[r * cols + c];
}
};
#include <limits> // std::numeric_limits
double find_max(const Matrix& m) {
// Initialize to the first element (matrix guaranteed non-empty by ctor)
double maxv = m.at(0, 0);
for (std::size_t r = 0; r < m.rows; ++r) {
for (std::size_t c = 0; c < m.cols; ++c) {
const double v = m.at(r, c);
if (v > maxv) maxv = v;
}
}
return maxv;
}
at() checks guard misuse during development.#include <iostream>
int main() {
Matrix m(3, 3);
m.at(0,0) = 1.0; m.at(0,1) = -4.2; m.at(0,2) = 2.5;
m.at(1,0) = 7.1; m.at(1,1) = 5.0; m.at(1,2) = -3.0;
m.at(2,0) = 0.0; m.at(2,1) = 3.3; m.at(2,2) = 6.9;
std::cout << "max = " << find_max(m) << '\n'; // expected 7.1
}
When designing tests, it is useful to know type bounds for edge cases.
#include <iostream>
#include <limits>
template<typename T>
void show_min_max() {
std::cout << "min: " << std::numeric_limits<T>::min()
<< " max: " << std::numeric_limits<T>::max() << '\n';
}
find_max<T>() to support any arithmetic type.at() with unchecked access in hot paths once validated.