You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求C++中基于自定义比较逻辑的多group交集元素获取函数

嘿,我来帮你搞定这个问题~

首先明确说:C++标准库并没有你描述的std::getgroup这种现成函数,不过我们完全可以基于你的自定义比较规则,自己实现一个符合需求的版本。

先理清楚你的核心需求:要从二维容器groups里,找出所有在每个group中都“存在”的thing元素——这里的“存在”是基于你的comparison函数的相似性规则(返回1或2就算相似)。下面是具体的实现思路和代码:

第一步:写一个辅助判断函数

用来检查某个thing是否在单个group中存在相似项:

bool isPresentInGroup(const thing& t, const group& g, int (*comp)(thing, thing)) {
    for (const auto& elem : g) {
        int compResult = comp(t, elem);
        // 只要两者相似(返回1或2),就算存在匹配
        if (compResult == 1 || compResult == 2) {
            return true;
        }
    }
    return false;
}

第二步:实现自定义的“交集”函数

这个函数会模拟你想要的getgroup功能,从所有group中筛选出共同存在的相似元素:

// 复用你定义的类型
typedef std::vector<thing> group;

group getCommonGroups(const std::vector<group>& groups, int (*comp)(thing, thing)) {
    // 边界处理:如果输入是空的,直接返回空结果
    if (groups.empty()) {
        return {};
    }

    // 把第一个group的元素作为初始候选集合
    group candidates = groups[0];

    // 遍历剩下的每个group,逐步筛选候选
    for (size_t i = 1; i < groups.size(); ++i) {
        group newCandidates;
        for (const auto& candidate : candidates) {
            // 只有当前候选在这个group里有相似项,才保留
            if (isPresentInGroup(candidate, groups[i], comp)) {
                newCandidates.push_back(candidate);
            }
        }

        // 如果某次筛选后候选为空,直接返回空(不可能有共同元素了)
        if (newCandidates.empty()) {
            return {};
        }

        candidates = std::move(newCandidates);
    }

    // 可选优化:对结果去重,每个相似组只保留最具体的元素
    group uniqueResults;
    for (const auto& t : candidates) {
        bool shouldAdd = true;
        for (auto& existing : uniqueResults) {
            int compRes = comp(t, existing);
            if (compRes == 1) {
                // t比现有元素更具体,替换掉现有元素
                existing = t;
                shouldAdd = false;
                break;
            } else if (compRes == 2) {
                // 现有元素比t更具体,跳过t
                shouldAdd = false;
                break;
            }
            // 返回0的话,两者不相似,继续检查下一个现有元素
        }
        if (shouldAdd) {
            uniqueResults.push_back(t);
        }
    }

    return uniqueResults;
}

调用方式

和你预想的逻辑一致,直接传入groups和你的comparison函数即可:

group commonThings = getCommonGroups(groups, comparison);

补充说明

  • 如果你不需要去重步骤(比如不在意结果里有相似的重复元素),可以直接去掉最后那段去重的代码,返回原始的candidates就行。
  • 如果你的需求是“找到每个group中最具体的共同相似元素”,还可以调整筛选逻辑,比如在检查每个group时,找到和候选最匹配的具体元素,再更新候选集合——这个可以根据你的实际业务场景微调。

内容的提问来源于stack exchange,提问作者Theo Walton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:22:55