patterncppMinor
Screen of chars
Viewed 0 times
screencharsstackoverflow
Problem
So its a class that lets you make a 'Screen' which is a n x n grid of chars. Your able to move a cursor by chosing the row and which column in the row and using that you can insert into into that place and change the char thats there.
#ifndef Screen_h
#define Screen_h
#include
#include
#include
#include
std::string makeString(const int, const char);
class Screen
{
public:
Screen() = default;
Screen(int num, char chr) { setRows(num, chr); }
void setRows(const int, const char); // Sets the rows and columns
void display() const; // Outputs the rows and columns
void moveCursor(int, int); // Lets user mover cursor but chosing the row and column
void insert(const char chr); // Using the cursors location you can change a character
private:
void setDefaultCursor(); // Sets the cursor to the character in the first row
std::string::iterator cursor; // The cursor
std::vector rows; // All the rows
};
// Member funtions
void Screen::setDefaultCursor() {
auto row = rows.begin();
cursor = row->begin();
}
void Screen::setRows(const int num, const char chr) {
rows.clear();
const std::string row = makeString(num, chr);
for (int cnt = 0; cnt != num; ++cnt) {
rows.push_back(row);
}
setDefaultCursor();
}
void Screen::display() const {
for (const auto c : rows) {
std::cout size() begin() + --AmmAccross;
}
void Screen::insert(const char chr) {
*cursor = chr;
}
// Non member function but still related funtions
std::string makeString(const int length, const char chr) {
std::string str;
for (int cnt = 0; cnt != length; ++cnt) {
str.push_back(chr);
}
return str;
}
#endifSolution
Your class looks quite good! There are some implementation details you can be more idiomatic with.
For
Also,
Let me also mention that in
For
setDefaultCursor, there is no need for a temporary variable:void Screen::setDefaultCursor()
{
cursor = rows.front().begin();
}Also,
makeString is obsolete. There is already such a constructor for std::string. Similarly, there is such a constructor for std::vector. So we can improve on setRows:void Screen::setRows(const int num, const char chr)
{
rows = std::vector(num, std::string(num, chr));
setDefaultCursor();
}Let me also mention that in
moveCursor, I think it's a bad habit to use statements that have side effects. Instead of saying e.g., "x += (--y)", just decrement y first, and then add it to x. This improves readability a lot.Code Snippets
void Screen::setDefaultCursor()
{
cursor = rows.front().begin();
}void Screen::setRows(const int num, const char chr)
{
rows = std::vector<std::string>(num, std::string(num, chr));
setDefaultCursor();
}Context
StackExchange Code Review Q#119828, answer score: 2
Revisions (0)
No revisions yet.