一种使用树结构优化switch语句的方法
介绍
在日常 装B 写代码中会经常用到if else if语句如:
if(1){
}
else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}else if(1){
//TODO
}
非常的麻烦,而且慢,我们可以用二分的思想去查找,如:
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
if(n<50){
if(n<25){
if(n<15){
cout<<"<15";
}
else{
cout<<">15";
}
}
else{
if(n>35){
cout<<"666";
}
else{
cout<<"666";
}
}
}
else{
if(n>75){
if(n>85){
cout<<"<85";
}
else{
cout<<">85";
}
}
else{
if(n>15){
cout<<"666";
}
else{
cout<<"666";
}
}
}
return 0;
}
这样我们就可以在
swith语句的条件非数字或没有固定范围时的解决方法
如果是字符串的话可以像字典树一样遍历到最后。这样也有优化。
思路核心
就是用二分的思想进行优化,减少判断,如果有其他思路欢迎评论!感谢!!!
这是mcr130102的博客,转载请注明出处
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!