c++坐标处理类

坐标移动

http://www.nowcoder.com/questionTerminal/119bcca3befb405fbe58abe9c532eb29

#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>
#include <regex>

using namespace std;

std::vector<std::string> split(const std::string& str, const std::string& del)
{
    std::regex re(del);
    std::vector<std::string> v(std::sregex_token_iterator(str.begin(), str.end(), re, -1),
    std::sregex_token_iterator());
    return v;
}

class Coordinate {
private:
    pair<int, int> coordinate;
    // key - (x, y)
    unordered_map<char, pair<int, int> > move_map;
    void initmap() {
        move_map['A'] = make_pair(-1, 0);
        move_map['D'] = make_pair(1, 0);
        move_map['S'] = make_pair(0, -1);
        move_map['W'] = make_pair(0, 1);

        move_map['a'] = make_pair(-1, 0);
        move_map['d'] = make_pair(1, 0);
        move_map['s'] = make_pair(0, -1);
        move_map['w'] = make_pair(0, 1);
    }
    bool isDigit(const string& str){
        bool bvalid = true;
        for (char c : str) {
            if (!isdigit(c))
            {
                bvalid = false;
                break;
            }
        }
        return bvalid;
    }
public:
    Coordinate() {
        initmap();
        coordinate.first = 0;
        coordinate.second = 0;
    }
    pair<int, int> process_key_move(string strs) {
        vector<string> v = split(strs, ";");
        for (string str : v) {
            if (str.size() <= 3 && str.size()>=2) {
                char ch = str[0];
                if (move_map.count(ch)) {
                    auto coord = move_map[ch];
                    str = str.substr(1);
                    if (isDigit(str))
                    {
                        int scale = stoi(str);
                        coordinate.first += scale * coord.first;
                        coordinate.second += scale * coord.second;
                    }
                }
            }
        }
        return coordinate;
    }

};

int main() {
    string str;
    while (cin>>str) {
        Coordinate coord;
        auto coordinate = coord.process_key_move(str);
        cout << coordinate.first << ',' \
            << coordinate.second << '\n';
    }

    return 0;
}
全部评论

相关推荐

10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务