c++ vector 添加结构体元素,检测结果坐标的几个写法

1、用向量vector ,添加的时候判断,相同名字的元素,置信度最大的框进行保存,如果有了就替换相关值,或者全部push 后遍历一遍删除相同的框子中,置信度最低的那个框

cpp 复制代码
// 检测 //
struct Detect
{
    std::string name;
    float prob;
    cv::Rect rect;
};


void add_det(std::vector<Detect>& dets)
// 输入引用类型的 数据方便修改
// 在每次添加的时候遍历判断一下,如果没有就添加,如果有,就比较判断更新最大的那个元素
{
    bool found = false;
    for (auto& det : dets) {
        if (det.name == label) {
            if (conf > det.prob) {
                det.prob = conf;
                det.rect = bbox;
            }
            found = true;
            break;
        }
    }

    if (!found) {
        dets.push_back({label, conf, bbox});
    }
 }



/
	std::vector<Detect> dets;

    std::string label = "狗";
    cv::Rect bbox(363, 388, 69, 57); //xywh
    float conf = 0.797;
    dets.push_back({label, conf, bbox});

    bbox = cv::Rect(366, 209, 101, 91); //xywh
    dets.push_back({"猫", 0.702, bbox});

    bbox = cv::Rect(113, 94, 533, 453); //xywh
    dets.push_back({"猫", 0.669, bbox});

2、用字典,添加自定义结构体变量框数据

cpp 复制代码
// std::map中的一个键值对。键值对由键和值组成,通过it->first可以访问键,通过it->second可以访问值
struct Detect
{
    std::string name;
    float prob;
    cv::Rect rect;
};
//


std::map<std::string, Detect> detectMap;

std::string label = "猫";
cv::Rect bbox(363, 388, 69, 57); //xywh
float conf = 0.797;

// 查找是否已存在相同标签的元素
auto it = detectMap.find(label);
if (it != detectMap.end()) {
    // 如果已存在,比较置信度并更新
    if (conf > it->second.prob) {
        it->second.prob = conf;
        it->second.rect = bbox;
    }
} else {
    // 如果不存在,添加新元素
    detectMap.insert({label, {label, conf, bbox}});
}

3、 重载操作符 opreate 写法

cpp 复制代码
//当你想要对自定义的结构体进行排序时,你可以通过重载operator<来定义排序的规则。
//以下是一个示例,展示了如何在结构体中重载operator<来按照置信度(prob)进行排序:

cpp
struct Detect {
    std::string name;
    float prob;
    cv::Rect rect;

    bool operator<(const Detect& other) const {
        return prob < other.prob;
    }
};

//在这个示例中,我们将operator<重载为比较两个Detect结构体的置信度(prob)大小。根据你的需求,你也可以选择比较其他的字段。

// 然后,你可以使用标准库中的排序算法(例如std::sort)对dets向量进行排序,如下所示:

cpp
std::vector<Detect> dets;

// 添加元素到dets...

std::sort(dets.begin(), dets.end());
这将使用重载的operator<来对dets中的元素进行排序,按照置信度从低到高的顺序进行排列。

希望这对你有帮助!👍🏻
相关推荐
无敌最俊朗@22 分钟前
解决 QML 中使用 Qt Charts 崩溃的三个关键步骤
开发语言·qt
会飞的小新30 分钟前
C 标准库之 <errno.h> 详解与深度解析
c语言·开发语言
胡八一1 小时前
30 分钟上手 exp4j:在 Java 中安全、灵活地计算数学表达式
java·开发语言·安全
郝学胜-神的一滴2 小时前
Linux 进程控制块(PCB)解析:深入理解进程管理机制
linux·服务器·开发语言
后端小张2 小时前
【鸿蒙开发手册】重生之我要学习鸿蒙HarmonyOS开发
开发语言·学习·华为·架构·harmonyos·鸿蒙·鸿蒙系统
胖咕噜的稞达鸭2 小时前
AVL树手撕,超详细图文详解
c语言·开发语言·数据结构·c++·算法·visual studio
CSCN新手听安2 小时前
【linux】多线程(六)生产者消费者模型,queue模拟阻塞队列的生产消费模型
linux·运维·服务器·c++
-SGlow-2 小时前
Linux相关概念和易错知识点(48)(epoll的底层原理、epoll的工作模式、反应堆模式)
linux·服务器·c语言·网络·c++
007php0072 小时前
百度面试题解析:synchronized、volatile、JMM内存模型、JVM运行时区域及堆和方法区(三)
java·开发语言·jvm·缓存·面试·golang·php
csdn_aspnet2 小时前
C++ 圆台体积和表面积计算程序(Program for Volume and Surface area of Frustum of Cone)
c++