Pointers/Memory Allocation   «Prev  Next»
Lesson 15 Dynamic Multidimensional Arrays
Objective Implement a safe, modern C++ find_max() for 2-D data and verify with simple tests.

Finding the Maximum Value in a Dynamic 2-D Array (Modern C++)

Main point: represent a 2-D matrix safely and write a clear, correct, and testable find_max() that works for any dimensions.

What needed improvement (Use Case 2 critique)

A simple, robust matrix type

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];
  }
};

find_max(): correct, fast, and self-contained

#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;
}

Why this works


C++ How to Program

Usage and quick verification

#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
}

Numeric type limits (reference)

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';
}

Complexity & extensions


SEMrush Software