Write a Matrix class that stores its elements in a private flat vector, offers at(r, c) with bounds checking (throwing std::out_of_range), and computes row sums without exposing its storage.
Solution
main.cpp
#include <iostream>
#include <stdexcept>
#include <vector>
class Matrix {
std::size_t rows_, cols_;
std::vector<int> data_;
std::size_t index(std::size_t r, std::size_t c) const {
if (r >= rows_ || c >= cols_) throw std::out_of_range("index out of range");
return r * cols_ + c;
}
public:
Matrix(std::size_t r, std::size_t c) : rows_(r), cols_(c), data_(r * c, 0) {}
int& at(std::size_t r, std::size_t c) { return data_[index(r, c)]; }
int at(std::size_t r, std::size_t c) const { return data_[index(r, c)]; }
std::vector<int> row_sums() const {
std::vector<int> s(rows_, 0);
for (std::size_t r = 0; r < rows_; ++r)
for (std::size_t c = 0; c < cols_; ++c) s[r] += data_[r * cols_ + c];
return s;
}
};
int main() {
Matrix m(2, 3);
int v = 1;
for (std::size_t r = 0; r < 2; ++r)
for (std::size_t c = 0; c < 3; ++c) m.at(r, c) = v++;
for (int s : m.row_sums()) std::cout << s << ' ';
try { m.at(2, 0) = 7; }
catch (const std::out_of_range& e) { std::cout << "| " << e.what() << '\n'; }
return 0;
}
Output Verified by compiling and running
6 15 | index out of range
Callers never learn that the data is a flat row-major vector – the class could switch to another layout without changing its interface. The private index helper is the single place where bounds are checked.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!