代码优化之简化if臃肿的判断条件

简化if判断条件

方法1:

#include <iostream>
#include <vector>
#include <functional>

// 封装参数的结构体
struct ConditionParams {
    int facenum;
    double zoomRatio;
    int iso;
    double facelv;
    int face_w;
    double qualityScore;
    int xx;
    int yy;
};

// 条件检查函数,使用 std::function
bool checkConditions(const ConditionParams& params) {
    std::vector<std::pair<std::function<bool(const ConditionParams&)>, std::string>> conditions = {
        {[](const ConditionParams& p) { return p.facenum < p.xx; }, "Face number condition failed."},
        {[](const ConditionParams& p) { return p.zoomRatio > p.xx; }, "Zoom ratio condition failed."},
        {[](const ConditionParams& p) { return p.iso < p.xx && p.iso > p.yy; }, "ISO condition failed."},
        {[](const ConditionParams& p) { return p.facelv > p.xx; }, "Face level condition failed."},
        {[](const ConditionParams& p) { return p.face_w > p.xx; }, "Face width condition failed."},
        {[](const ConditionParams& p) { return p.qualityScore > p.xx; }, "Quality score condition failed."}
    };

    // 逐个检查条件
    for (const auto& [checker, errorMessage] : conditions) {
        if (!checker(params)) {
            std::cerr << errorMessage << std::endl;
            return false;
        }
    }
    return true;
}

int main() {
    // 输入的参数
    ConditionParams params = {5, 2.0, 400, 1.5, 60, 0.95, 10, 100};

    // 检查条件
    if (checkConditions(params)) {
        std::cout << "All conditions met." << std::endl;
    } else {
        std::cout << "Some conditions failed." << std::endl;
    }

    return 0;
}
  • std::function:使用 std::function<bool(const ConditionParams&)> 取代了函数指针,使得 lambda 表达式更加灵活。
  • ConditionParams 结构体:将所有条件判断的输入参数封装在 ConditionParams 结构体中,使得代码简洁且易于扩展。
  • 简洁的条件检查流程:通过 for 循环遍历所有条件并逐个检查,每个条件不满足时打印对应的错误信息,便于调试。

方法2:

  • 将每个条件提取到独立的函数中:这样每个条件的逻辑更加清晰。
  • 提供清晰的日志或调试信息:当某个条件未通过时,可以打印出相关的错误或状态信息。
  • 使用可读性更好的结构:比如,链式调用或结构体方式,使条件检查更具语义化。
#include <iostream>

bool checkFaceNum(int facenum, int threshold) {
    if (facenum < threshold) {
        std::cout << "Check failed: facenum < " << threshold << std::endl;
        return false;
    }
    return true;
}

bool checkZoomRatio(float zoomRatio, float threshold) {
    if (zoomRatio <= threshold) {
        std::cout << "Check failed: zoomRatio <= " << threshold << std::endl;
        return false;
    }
    return true;
}

bool checkIsoRange(int iso, int minThreshold, int maxThreshold) {
    if (iso < minThreshold || iso > maxThreshold) {
        std::cout << "Check failed: iso out of range [" << minThreshold << ", " << maxThreshold << "]" << std::endl;
        return false;
    }
    return true;
}

bool checkFaceLevel(float facelv, float threshold) {
    if (facelv <= threshold) {
        std::cout << "Check failed: facelv <= " << threshold << std::endl;
        return false;
    }
    return true;
}

bool checkFaceWidth(float face_w, float threshold) {
    if (face_w <= threshold) {
        std::cout << "Check failed: face_w <= " << threshold << std::endl;
        return false;
    }
    return true;
}

bool checkQualityScore(float qualityScore, float threshold) {
    if (qualityScore <= threshold) {
        std::cout << "Check failed: qualityScore <= " << threshold << std::endl;
        return false;
    }
    return true;
}

bool allConditionsMet(int facenum, float zoomRatio, int iso, float facelv, float face_w, float qualityScore) {
    return checkFaceNum(facenum, 10) &&    // 假设阈值为 10
           checkZoomRatio(zoomRatio, 1.5) &&   // 假设阈值为 1.5
           checkIsoRange(iso, 100, 800) &&    // 假设iso范围为100-800
           checkFaceLevel(facelv, 0.8) &&    // 假设facelv阈值为 0.8
           checkFaceWidth(face_w, 50) &&     // 假设face_w阈值为 50
           checkQualityScore(qualityScore, 0.9);  // 假设质量分数阈值为 0.9
}

int main() {
    int facenum = 9;
    float zoomRatio = 2.0;
    int iso = 400;
    float facelv = 1.0;
    float face_w = 55.0;
    float qualityScore = 0.95;

    if (allConditionsMet(facenum, zoomRatio, iso, facelv, face_w, qualityScore)) {
        std::cout << "All conditions met, proceeding..." << std::endl;
    } else {
        std::cout << "Conditions not met, please check the logs for details." << std::endl;
    }

    return 0;
}

方法3:

如果条件很多,可以使用结构体封装输入参数,并通过链式方法实现条件检查。

#include <iostream>

struct ConditionChecker {
    int facenum;
    float zoomRatio;
    int iso;
    float facelv;
    float face_w;
    float qualityScore;

    bool checkFaceNum(int threshold) {
        if (facenum < threshold) {
            std::cout << "Check failed: facenum < " << threshold << std::endl;
            return false;
        }
        return true;
    }

    bool checkZoomRatio(float threshold) {
        if (zoomRatio <= threshold) {
            std::cout << "Check failed: zoomRatio <= " << threshold << std::endl;
            return false;
        }
        return true;
    }

    bool checkIsoRange(int minThreshold, int maxThreshold) {
        if (iso < minThreshold || iso > maxThreshold) {
            std::cout << "Check failed: iso out of range [" << minThreshold << ", " << maxThreshold << "]" << std::endl;
            return false;
        }
        return true;
    }

    bool checkFaceLevel(float threshold) {
        if (facelv <= threshold) {
            std::cout << "Check failed: facelv <= " << threshold << std::endl;
            return false;
        }
        return true;
    }

    bool checkFaceWidth(float threshold) {
        if (face_w <= threshold) {
            std::cout << "Check failed: face_w <= " << threshold << std::endl;
            return false;
        }
        return true;
    }

    bool checkQualityScore(float threshold) {
        if (qualityScore <= threshold) {
            std::cout << "Check failed: qualityScore <= " << threshold << std::endl;
            return false;
        }
        return true;
    }

    // 链式条件检查
    bool allConditionsMet() {
        return checkFaceNum(10) &&
               checkZoomRatio(1.5) &&
               checkIsoRange(100, 800) &&
               checkFaceLevel(0.8) &&
               checkFaceWidth(50) &&
               checkQualityScore(0.9);
    }
};

int main() {
    ConditionChecker checker = {9, 2.0, 400, 1.0, 55.0, 0.95};

    if (checker.allConditionsMet()) {
        std::cout << "All conditions met, proceeding..." << std::endl;
    } else {
        std::cout << "Conditions not met, please check the logs for details." << std::endl;
    }

    return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/900098.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【Power Query】List.Select 筛选列表

List.Select 筛选列表 ——在列表中返回满足条件的元素 List.Select(列表,判断条件) 不是列表的可以转成列表再筛选&#xff0c;例如 Record.ToList 不同场景的判断条件参考写法 (1)单条件筛选 列表中小于50的数字 List.Select({1,99,8,98,5},each _<50) (2)多条件筛…

39.3K Star,一个现代的数据库ORM工具,专为Node.js和TypeScript设计

大家好&#xff0c;今天给大家分享一个现代的数据库对象关系映射&#xff08;Object-Relational Mapping&#xff0c;ORM&#xff09;工具Prisma ORM&#xff0c;它旨在简化数据库操作&#xff0c;提高开发效率&#xff0c;并确保类型安全。 项目介绍 Prisma ORM适用于各种需要…

在Windows 10操作系统中搭建FTP

在Windows 10操作系统中搭建FTP&#xff08;File Transfer Protocol&#xff0c;文件传输协议&#xff09;服务器&#xff0c;可以为局域网内的用户提供文件共享和传输服务。以下是详细的搭建步骤&#xff0c;包括准备工作、安装与配置FTP服务、以及测试与访问FTP服务器等环节。…

HarmonyOS第一课——HarmonyOS介绍

HarmonyOS第一课 HarmonyOS介绍 HarmonyOS是新一代的智能终端操作系统&#xff08;泛终端服务的载体&#xff09;&#xff1b; 智慧互联协同&#xff0c;全场景交互体验&#xff1b; 核心技术理念&#xff1a; 一次开发 多次部署&#xff1a; 预览 可视化开发UI适配 事件交…

关闭或开启Win11系统的自动更新

Win11系统老是自动更新&#xff0c;每次更新后不仅拖慢计算机的运行速度&#xff0c;甚至打印机都无法使用了&#xff0c;给我们带来了很多困扰。 那么我们该如何彻底关闭Win11系统的自动更新呢&#xff1f;关闭Win11系统自动更新会有什么弊端呢&#xff1f; 下面就分享几个小方…

笛卡尔空间内的阻抗控制

目录 1. 笛卡尔空间内的阻抗控制方程推导2. 笛卡尔空间内的阻抗控制的控制框图3. 一些变体变体 1.1变体 1.2变体 2 4.笛卡尔空间内的阻抗控制方法总结参考资料 1. 笛卡尔空间内的阻抗控制方程推导 目标&#xff1a;让机器末端执行器在笛卡尔空间内的每个方向上都体现出由弹簧阻…

Java-线程池技术

一、线程池简介 线程池是一种池化的思想&#xff0c;是将一些共同资源放到池中进行管理和使用&#xff0c;从而避免大量的创建销毁带来的资源浪费等问题&#xff0c;线程池主要优点体现在&#xff1a; 降低资源消耗&#xff1a;普通线程创建执行完任务之后即被销毁&#xff0…

【C++】类和对象(附题)

目录 一、类的定义 1.1.类定义格式 1.2.访问限定符 1.3.类域 二、实例化 2.1.实例化概念 2.2.对象大小 三、this指针 附加题&#xff1a;&#xff08;增进对this指针的理解&#xff09; 1.下面程序编译运行结果是&#xff08;&#xff09; 2.下面程序编译运行结果是&…

linux下gpio模拟spi时序

目录 前言一、配置内容二、驱动代码实现三、总结 前言 本笔记总结linux下使用gpio模拟spi时序的方法&#xff0c;基于arm64架构的一个SOC&#xff0c;linux内核版本为linux5.10.xxx&#xff0c;以驱动三线spi(时钟线sclk&#xff0c;片选cs&#xff0c;sdata数据读和写使用同一…

antv g6问题处理汇总

关于自定义边时&#xff0c;箭头始终没出现的问题处理 问题&#xff1a; 问题对应的代码 解决方法&#xff1a;将箭头的偏移量调整y坐标 完整代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8" /><title&…

使用vue+kkFileview组件实现各种类型文件预览

关于kkFileView 【参考】&#xff1a;https://kkfileview.keking.cn/zh-cn/docs/home.html 文档在线预览项目解决方案&#xff0c;项目使用流行的spring boot搭建&#xff0c;易上手和部署。万能的文件预览开源项目&#xff0c;基本支持主流文档格式预览 本项目介绍 项目使用…

无忧树闪耀2024中国防水展:智能新材料,引领新赛道!

2024年10月16日&#xff0c;上海无忧树新材料科技有限公司在上海国家会展中心5.2号馆5103展位&#xff0c;成功亮相2024中国国际屋面和建筑防水技术展览会。作为新材料科技领域的佼佼者&#xff0c;无忧树以创新的技术、卓越的产品和专业的服务&#xff0c;赢得了现场观众的广泛…

COVON全意卫生巾,轻薄透气,绵柔速干,马来西亚热销中

随着女性健康意识的提高&#xff0c;卫生巾作为女性日常生活中的必需品&#xff0c;其品质和舒适度越来越受到关注。今天&#xff0c;我们要为大家介绍一款来自马来西亚热销的卫生巾——COVON全意卫生巾&#xff0c;以其轻薄透气、绵柔速干的特点&#xff0c;赢得了广大女性的喜…

【有啥问啥】视频插帧算法技术原理详解

视频插帧算法技术原理详解 引言 视频插帧&#xff08;Video Interpolation&#xff09;技术&#xff0c;作为计算机视觉领域的一项重要应用&#xff0c;旨在通过算法手段在已有的视频帧之间插入额外的帧&#xff0c;从而提升视频的帧率&#xff0c;使其看起来更加流畅。这一技…

oracle19c的k8s部署

前提条件 1、首先要有一个oracle 账号 2、需要一台能连接网络并安装docker的机器用Oracle账号登录Home 点击database 跳转到下一个页面 记得一定sign in ,否则无法拉取镜像 docker pull container-registry.oracle.com/database/enterprise:latest 执行拉取后使用镜像进行部…

基于Ubuntu24.04,下载并编译Android12系统源码 (二)

1. 前言 上篇文章&#xff0c;我们基于Ubuntu24.04&#xff0c;已经成功下载下来了Android12的源码&#xff0c;这篇文章我们会接着上文&#xff0c;基于Ubuntu24.04来编译Android源码。 2. 编译源码 2.1 了解源码编译的名词 Makefile &#xff1a; Android平台的一个编译系…

Diffusion Probabilistic Models for 3D Point Cloud Generation——点云论文阅读(8)

此内容是论文总结&#xff0c;重点看思路&#xff01;&#xff01; 文章概述 该文献介绍了一种用于3D点云生成的概率模型。点云是表示3D物体和场景的常用方式&#xff0c;但由于其不规则的采样模式&#xff0c;与图像相比&#xff0c;点云生成更具挑战性。现有方法如GANs、流…

Flutter通过showDialog实现下拉筛选菜单效果

一、效果图 二、 实现方式 获取固定在顶部筛选头部Widget在屏幕上的位置和它的高度在弹窗中通过获取到的高度进行内容显示区域定位巧用AnimatedContainer组件实现下拉动画效果最后在底部加上黑色蒙层 unawaited(showDialog(context: context,useSafeArea: false,barrierColor…

Golang | Leetcode Golang题解之第503题下一个更大元素II

题目&#xff1a; 题解&#xff1a; func nextGreaterElements(nums []int) []int {n : len(nums)ans : make([]int, n)for i : range ans {ans[i] -1}stack : []int{}for i : 0; i < n*2-1; i {for len(stack) > 0 && nums[stack[len(stack)-1]] < nums[i%…

vue2-render:vue2项目使用render / 基础使用

一、本文内容 本文内容记录render常用的一些属性和方法的配置&#xff0c;以作参考 export default { data() {return { modelValue: ,key: 0,}; }, render(h) { return h(div, [ h(input, {class: input,attrs: { type: text }, key: this.key,props: { value: thi…