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; }