C++,codewars,Directions Reduction,550f22f4d758534c1100025a

/*
codewars,Directions Reduction,550f22f4d758534c1100025a
给定一个数组,数组中的元素是方向,例如["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"],
相邻的两个元素若方向相反可以抵消,例如"NORTH"和"SOUTH"可以抵消,"EAST"和"WEST"可以抵消,
最终返回一个数组,数组中的相邻元素均不能抵消例如["WEST"]。
*/
#include <vector>
#include <string>
#include <map>
class DirReduction
{
public:
//static: 类中声明的静态成员变量或静态成员函属于类本身, 而不属于类的某个对象
//静态成员变量在所有对象之间是共享的,
//静态成员函数可以在没有对象实例的情况下调用
static std::vector<std::string> dirReduc(std::vector<std::string> &arr){
const std::map<std::string, std::string> opposite = {{"NORTH", "SOUTH"}, {"SOUTH", "NORTH"}, {"EAST", "WEST"}, {"WEST", "EAST"}};
std::vector<std::string> result;
for(auto& direction : arr){
// if(result.empty() || result.back() != opposite[direction]){
// std::map的 operator[]不适用于const对象, 因为 operator[]可能会插入新元素, 而const对象不允许修改
// 使用const声明一个常量对象, 该对象的成员变量不能被修改, 并且只能调用const成员函数
// 常量对象只能调用常量成员函数, 常量成员函数(const成员函数)不能修改对象的成员变量
if(result.empty() || result.back()!=opposite.at(direction)){
result.push_back(direction);
}else{
result.pop_back();
}
}
return result;
}
};
posted @   Kazuma_124  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示