I m 为汇编者撰写前端,目前正在实施校正仪扫描功能。 我将使用<代码>Punctuator等舱,代表我方的输入源文档中的教员,此外,它也是一些静态扫描方法的所在地。 这里是辅导员。
#ifndef PUNCTUATOR_H_
#define PUNCTUATOR_H_
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include "reserved_component.h"
enum class PunctuatorEnum {
OPEN_BRACE,
CLOSE_BRACE,
TERMINATOR,
EQUAL,
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
};
class Punctuator : public ReservedComponent {
public:
Punctuator(std::string lexeme);
Punctuator(Punctuator&& punctuator);
static bool IsPunctuator(std::string buffer);
static PunctuatorEnum ForLexeme(std::string buffer);
private:
PunctuatorEnum punctuator_enum;
static std::unordered_map<std::string, PunctuatorEnum> dictionary;
};
#endif // PUNCTUATOR_H_
由于你能够使用静态<代码>unordered_map,储存可能的旁听器的“字典”,然后使用该地图检查某一方的护卫是否代表旁人。 我将地图放在旁边,c 在这里:
#include "punctuator.h"
std::unordered_map<std::string, PunctuatorEnum> Punctuator::dictionary = {
{ "{", PunctuatorEnum::OPEN_BRACE },
{ "}", PunctuatorEnum::CLOSE_BRACE },
{ ".", PunctuatorEnum::TERMINATOR },
{ "=", PunctuatorEnum::EQUAL },
{ "+", PunctuatorEnum::PLUS },
{ "-", PunctuatorEnum::MINUS },
{ "*", PunctuatorEnum::MULTIPLY },
{ "/", PunctuatorEnum::DIVIDE }
};
Punctuator::Punctuator(std::string lexeme) : ReservedComponent(lexeme) {
this->punctuator_enum = dictionary.at(lexeme);
}
Punctuator::Punctuator(Punctuator&& punctuator) : ReservedComponent(std::move(punctuator)) {
this->punctuator_enum = std::move(punctuator.punctuator_enum);
}
bool Punctuator::IsPunctuator(std::string buffer) {
return dictionary.contains(buffer);
}
PunctuatorEnum Punctuator::ForLexeme(std::string lexeme) {
return dictionary.at(lexeme);
}
I understand this is not the cleanest approach as this forces me to maintain the PunctuatorEnum
and the unordered map, but it s what I ve chosen so far. I d also like to implement a method StartsPunctuator(char c)
to check whether a given char starts a punctuator.
My question is as follows: Is it possible to declare a static unordered_set
variable in my Punctuator
class, say punctuator_first_char
, and have it initialized to store only the first chars of every entry of the key-set of the static member variable dictionary
? This way I would be able to simply call the contains
method on punctuator_first_char
in my StartsPunctuator(char ch)
method without having to iterate through dictionary
.