首页
学习
活动
专区
圈层
工具
发布

炭筛
EN

Code Review用户
提问于 2016-02-12 23:22:27
回答 1查看 64关注 0票数 4

因此,它是一个类,它允许您创建一个“屏幕”,这是一个由字符组成的n×n网格。您可以通过选择行和行中的哪个列来移动游标,并使用它可以插入到该位置并更改那里的字符。

代码语言:javascript
复制
#ifndef Screen_h
#define Screen_h

#include <vector>
#include <string>
#include <iostream>
#include <stdexcept>

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<std::string> 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 << c << '\n';
    }
}

void Screen::moveCursor(int AmmRow, int AmmAccross) {
    if (rows.size() < AmmRow || rows.begin()->size() < AmmAccross) {
        throw std::runtime_error("Cursor move is too big");
    }
    auto row = (rows.begin() + --AmmRow);
    cursor = row->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;
}

#endif
EN

回答 1

Code Review用户

发布于 2016-02-13 13:52:42

你的课看上去不错!有一些实现细节,您可以更习惯于使用。

对于setDefaultCursor,不需要临时变量:

代码语言:javascript
复制
void Screen::setDefaultCursor() 
{
    cursor = rows.front().begin();
}

而且,makeString已经过时了。std::string已经有了这样一个构造函数。类似地,std::vector也有这样的构造函数。因此,我们可以改进setRows

代码语言:javascript
复制
void Screen::setRows(const int num, const char chr) 
{
    rows = std::vector<std::string>(num, std::string(num, chr));
    setDefaultCursor();
}

让我也提一下,在moveCursor中,我认为使用有副作用的语句是一个坏习惯。不是说"x += (-y)“,而是先将y递减,然后将其添加到x中。这大大提高了可读性。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/119828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档