#include <QCoreApplication>
#include <iostream>
#include <cstring>
#include <unordered_set>
#include <numeric>
#include <vector>
#include <unordered_set>
class Expression
{
public:
virtual bool Interpret(std::string mess) = 0;
};
class TerminaExpression : public Expression
{
public:
TerminaExpression(std::vector<std::string> info)
{
foreach (auto &e, info)
{
m_set.insert(e);
qDebug() << m_set.size() << Qt::endl;
}
}
bool Interpret(std::string mess) override
{
for(const auto &e : m_set)
{
qDebug() << "pos1 : " << QString::fromUtf8(e.c_str()) << Qt::endl;
}
auto got = m_set.find(mess);
if(got == m_set.end())
{
qDebug() << "查无此人 或 学校" << Qt::endl;
return false;
}
else
{
qDebug() << "找到了" << QString::fromUtf8((*got).c_str()) << Qt::endl;
return true;
}
}
private:
std::unordered_set<std::string> m_set;
};
class AndExpression : public Expression
{
public:
AndExpression(Expression *school, Expression *student)
{
m_school = school;
m_student = student;
}
std::vector<std::string> split(std::string s, std::string seprate)
{
std::vector<std::string> ret;
int seprate_len = seprate.length();
int start = 0;
int index;
while((index = s.find(seprate, start)) != -1)
{
ret.push_back(s.substr(start, index - start));
start = index + seprate_len;
}
if(start < s.length())
ret.push_back(s.substr(start, s.length() - start));
return ret;
}
bool Interpret(std::string mess)
{
std::vector<std::string> s = split(mess, "的");
qDebug() << "s[0]: " << QString::fromUtf8(s[0].c_str()) << ", s[1]: " << QString::fromUtf8(s[1].c_str()) << Qt::endl;
return m_school->Interpret(s[0]) && m_student -> Interpret(s[1]);
}
private:
Expression *m_school;
Expression *m_student;
};
class Context
{
public:
Context()
{
Expression *school = new TerminaExpression(schools);
Expression *student = new TerminaExpression(students);
schoolStudent = new AndExpression(school, student);
}
void enterCan(std::string mess)
{
bool ok = schoolStudent->Interpret(mess);
if(ok)
qDebug() << "这个学生是 " << QString::fromUtf8(mess.c_str()) << "可以进入校园!" << Qt::endl;
else
qDebug() << QString::fromUtf8(mess.c_str()) << "不可以进入校园!" << Qt::endl;
}
private:
std::vector<std::string> schools = {"QH", "BD"};
std::vector<std::string> students = {"明明", "红红", "蓝蓝"};
Expression *schoolStudent;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Context *per = new Context();
per->enterCan("QH的明明");
per->enterCan("BD的东东");
delete per;
return a.exec();
}
11-07
988

08-03
840

08-03
944
