泛化布尔函数以获得更优雅的代码
Generalising Boolean Functions for more elegant code
我一直认为,如果你正在复制和粘贴代码,那么有一个更优雅的解决方案。我目前正在C++中实现一个字符串后缀trie,并且有两个几乎相同的函数,它们仅在返回语句上有所不同。
第一个函数检查子字符串是否存在,第二个函数检查它是否是后缀(所有字符串都有字符#
添加到末尾)。
子字符串(字符串 S)
bool Trie::substring(string S){
Node* currentNode = &nodes[0]; //root
for(unsigned int i = 0; i < S.length(); i++){
int edgeIndex = currentNode->childLoc(S.at(i));
if(edgeIndex == -1)
return false;
else currentNode = currentNode->getEdge(edgeIndex)->getTo();
}
return true;
}
后缀(字符串 S)
bool Trie::suffix(string S){
Node* currentNode = &nodes[0]; //root
for(unsigned int i = 0; i < S.length(); i++){
int edgeIndex = currentNode->childLoc(S.at(i));
if(edgeIndex == -1)
return false;
else currentNode = currentNode->getEdge(edgeIndex)->getTo();
}
return (currentNode->childLoc('#') == -1)? false : true; //this will be the index of the terminating character (if it exists), or -1.
}
如何才能更优雅地概括逻辑?也许使用模板?
在这种情况下,我个人所做的是将通用代码移动到函数中,我从多个地方调用该函数,我需要的地方,说通用功能。考虑一下:
Node* Trie::getCurrentNode (string S){
Node* currentNode = &nodes[0];
for(unsigned int i = 0; i < S.length(); i++){
int edgeIndex = currentNode->childLoc(S.at(i));
if(edgeIndex == -1)
return nullptr;
else currentNode = currentNode->getEdge(edgeIndex)->getTo();
}
return currentNode;
}
然后,在所有情况下,在您需要的地方使用它:
bool Trie::substring(string S){
return getCurrentNode (S) != nullptr;
}
bool Trie::suffix(string S){
Node* currentNode = getCurrentNode(S);
return currentNode != nullptr && currentNode->childLoc('#') != -1;
// I decided to simplify the return statement in a way François Andrieux suggested, in the comments. It makes your code more readable.
}
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 带有布尔数组成员的 C++ 结构.如何在主代码中使用
- 任何可以在单个 CPU 指令中在 0 和 1 之间翻转位/整数/布尔值的可能代码
- 泛化布尔函数以获得更优雅的代码
- 代码块布尔错误
- C++ 嵌套'if'语句中的所有代码都会运行,即使这会更改外部语句的布尔值?
- 我的代码中的错误 - 布尔真值表
- 将布尔值转换为字符会产生错误和代码中断
- 这段c++代码是如何处理不寻常的单个布尔语句的?
- 由于在返回语句中使用了布尔或操作,因此递归如何对以下代码工作