c++ - 为什么 count 不能为一组 C++ 对象返回正确的值?

标签 c++

我有一个包含结构数据元素的集合对象。但是,当对象不包含在集合对象中时,计数似乎返回“1”。它似乎只查看结构的第一个元素。我究竟做错了什么?这是我的代码示例:

我也实现了“<”和“==”运算符:

struct drugKey_tp { std::string alert_uuid;
                    std::string patient_id;
                    std::string claim_id;
                    std::string ndc_code;
 };
 inline bool operator<(const drugKey_tp &lhs,
                       const drugKey_tp &rhs) {
     return (lhs.alert_uuid < rhs.alert_uuid &&
             lhs.ndc_code < rhs.ndc_code &&
             lhs.claim_id < rhs.claim_id &&
             lhs.ndc_code < rhs.ndc_code);
 };
 inline bool operator==(const drugKey_tp &lhs, const drugKey_tp &rhs) {
     return (lhs.alert_uuid == rhs.alert_uuid &&
             lhs.patient_id == rhs.patient_id && 
             lhs.claim_id == rhs.claim_id &&
             lhs.ndc_code == rhs.ndc_code);
 };

这是我检查对象是否存在的地方,如果不存在则添加它们:

drugKey_tp drugKey;
static set<drugKey_tp> savedRxDetails; 
...
drugKey.alert_uuid = <some value>;
drugKey.patient_id = <some value>;
drugKey.claim_id = <some value>;
drugKey.ndc_code = <some value>;


   if (savedRxDetails.count(drugKey) == 0) {
       // Save the detail if this detail has not been saved
       savedRxDetails.insert(drugKey);      
    }
    else {
        return;
    }

我在“savedRxDetails”中添加了以下四个值:

alert id   = E51ED799-10C5-475F-9474-1A403B85A83C
patient_id = 4513004328217
claim_id   = 126872102351
ndc_code   = 55111059430

然后下一次调用此代码,检查以下结构值以查看它们是否存在于 saveRxDetails 中。当我使用以下值调用“savedRxDetails.count(drugKey)”时,返回值为“1”:

 alert id   = E51ED799-10C5-475F-9474-1A403B85A83C
 patient_id = 4513004328217
 claim_id   = 114225128231
 ndc_code   = 00006027531

您可以看到结构的第一个元素 (alert_id) 和第二个元素 (patient_id) 匹配,但其余元素都不匹配。我是否需要实现除“<”和“==”之外的其他运算符才能使“count”方法正常工作?

最佳答案

您没有正确实现比较。您应该只比较第一个不同的字段:

if (lhs.alert_uuid != rhs.alert_uuid)
    return lhs.alert_uuid < rhs.alert_uuid;
else if (lhs.ndc_code != rhs.ndc_code)
    return lhs.ndc_code < rhs.ndc_code;
else if ( /* etc ... */ )

使用 std::tuple's comparison 更容易做到这一点:

#include <tuple>

return
    std::tie(lhs.alert_uuid, lhs.ndc_code, lhs.claim_id, lhs.patient_id) <
    std::tie(rhs.alert_uuid, rhs.ndc_code, rhs.claim_id, rhs.patient_id);

关于c++ - 为什么 count 不能为一组 C++ 对象返回正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195487/

相关文章:

c++ - Boost.MPI recv 到现有 vector 的切片中

c++ - antlr4中的ParseTree遍历

c++ - 对象具有阻止匹配的类型限定符(未找到函数重载)

c++ - Qt QCombobox 更改滚动箭头

c++ - 如何编写可以返回迭代器或反向迭代器的 C++ 函数

c++ - 无论如何在模板参数上有一个decltype?

c++ - SWIG, boost 共享指针和继承

c++ - 我的循环可以再优化吗?

c++ - 对齐的内存分配器: memory corruption (game engine architecture[Jason Gregory])

c++ - 使用 OpenCV 随机森林进行回归