Fishtank
shape.cpp
Go to the documentation of this file.
1 #include "shape.h"
2 #include <stdexcept>
3 
4 using std::string;
5 using std::vector;
6 
7 const char kPadChar = ' ';
8 
9 Shape::Shape(vector<string> shape) {
10  if (shape.size() == 0) {
11  return;
12  }
13  shape_ = shape;
14  size_t max_width = shape_[0].size();
15  // Find max width
16  for (size_t i = 1; i < shape_.size(); i++) {
17  if (shape_[i].length() > max_width) {
18  max_width = shape_[i].length();
19  }
20  }
21  // Right-pad all lines to be that width
22  for (size_t i = 0; i < shape_.size(); i++) {
23  if (shape_[i].length() < max_width) {
24  shape_[i] = shape_[i] + string(max_width - shape_[i].length(), kPadChar);
25  }
26  }
27 }
28 
29 int Shape::width() const { return height() == 0 ? 0 : shape_[0].length(); }
30 
31 int Shape::height() const { return shape_.size(); }
32 
33 char Shape::charAt(int col, int row) const {
34  if (col < 0) {
35  throw std::out_of_range("col must be nonnegative");
36  }
37  if (col >= width()) {
38  throw std::out_of_range("col must be < width");
39  }
40  if (row < 0) {
41  throw std::out_of_range("row must be nonnegative");
42  }
43  if (row >= height()) {
44  throw std::out_of_range("row must be < height");
45  }
46  return shape_[row][col];
47 }
Shape(std::vector< std::string > shape)
Take in an array of lines and right-pad the shorter ones with ' ' to the width of the longest line.
Definition: shape.cpp:9
char charAt(int col, int row) const
Fetch the character at the given coordinate pair.
Definition: shape.cpp:33
int width() const
Definition: shape.cpp:29
int height() const
Definition: shape.cpp:31
const char kPadChar
Definition: shape.cpp:7