我正在构建一个确定性有限自动机,作为学校的词法分析器。我没有在哈希表中列出每个可能的状态转换,而是如果在该表中找不到该状态的条目,我想要一个全部拒绝状态。我的程序似乎认识到整数字符而不是字母字符。此外,当将状态返回到main()
时,我得到一个随机整数而不是预期状态。任何见解将不胜感激。这是我用来说明问题的简要代码:
#include <iostream>
#include <unordered_map>
using std::cout;
int calculateNextState(int current_state, char letter);
int main() {
char key = 'h';
int current_state = 0;
int new_state = 0;
new_state = calculateNextState(current_state, key);
cout << "The new state is: " << new_state << '\n';
return 0;
}
int calculateNextState(int current_state, char key) {
int new_state = current_state;
std::unordered_map<char, int> hashtable0;
hashtable0.emplace('0', 1);
hashtable0.emplace('1', 1);
hashtable0.emplace('2', 1);
hashtable0.emplace('3', 1);
hashtable0.emplace('4', 1);
hashtable0.emplace('5', 1);
hashtable0.emplace('6', 1);
hashtable0.emplace('7', 1);
hashtable0.emplace('8', 1);
hashtable0.emplace('9', 1);
hashtable0.emplace('.', 1);
hashtable0.emplace('$', 4);
hashtable0.emplace('_', 4);
hashtable0.emplace('a' || 'A', 4);
hashtable0.emplace('b' || 'B', 4);
hashtable0.emplace('c' || 'C', 4);
hashtable0.emplace('d' || 'D', 4);
hashtable0.emplace('e' || 'E', 4);
hashtable0.emplace('f' || 'F', 4);
hashtable0.emplace('g' || 'G', 4);
hashtable0.emplace('h' || 'H', 4);
hashtable0.emplace('i' || 'I', 4);
hashtable0.emplace('j' || 'J', 4);
hashtable0.emplace('k' || 'K', 4);
hashtable0.emplace('l' || 'L', 4);
hashtable0.emplace('m' || 'M', 4);
hashtable0.emplace('n' || 'N', 4);
hashtable0.emplace('o' || 'O', 4);
hashtable0.emplace('p' || 'P', 4);
hashtable0.emplace('q' || 'Q', 4);
hashtable0.emplace('r' || 'R', 4);
hashtable0.emplace('s' || 'S', 4);
hashtable0.emplace('t' || 'T', 4);
hashtable0.emplace('u' || 'U', 4);
hashtable0.emplace('v' || 'V', 4);
hashtable0.emplace('w' || 'W', 4);
hashtable0.emplace('x' || 'X', 4);
hashtable0.emplace('y' || 'Y', 4);
hashtable0.emplace('z' || 'Z', 4);
switch(current_state) {
case 0:
cout << "The count of the letter 'h': " << hashtable0.count(key) << '\n';
cout << "The count of an integer: " << hashtable0.count('0') << '\n';
if(hashtable0.count(key) != 0) //check if key is in hashtable
new_state = hashtable0[key];
else
new_state = -1; //return reject state if not found
break;
return new_state;
}
}
输出:
The count of the letter 'h': 0
The count of an integer: 1
The new state is: 3341764
答案 0 :(得分:1)
这不像你认为的那样工作:
'a' || 'A'
这是逻辑OR运算符。两个操作数都将转换为bool
,它们都会产生true
(因为它们都非零)。表达式的结果是true
,它转换回char
,得到1。
进行测试hashtable0.count(1)
,它会返回您通过这种方式进行的插入次数('a' || 'A', 'b' || 'B',...
它们都是相同的。)