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

C++中如何统计map迭代器下各AnimalWeightCAT对应的不同距离条目数

实现方法

要统计迭代器adit指向的每个AnimalWeightCAT下的不同距离条目数,直接调用内层map的size()方法即可:

  • adit->second是当前体重分类对应的内层map,存储该分类下所有距离和其出现次数的键值对
  • std::map的键天然唯一,每个不同距离只会在内层map存一条记录,size()返回的键总数就是去重后的距离条目数,和需要的统计值完全匹配。

把原来遍历内层map打印每个距离的逻辑删掉,直接输出adit->second.size()就能得到目标格式的结果。

修改后可直接运行的代码
#include <iostream>
#include <map>
#include <sstream>

int main() {
    std::istringstream file(
        "3 138 3 239 3 440 3 241 3 462 3 432 3 404 2 435 2 514 2 565 3 328 3 "
        "138 5 401 5 142 5 404 5 460 5 472 2 418 5 510 2");

    typedef int AnimalWeightCAT_t;
    typedef int distance_t;
    typedef int count_t;
    typedef std::map<distance_t, count_t> distcount_t;
    typedef std::map<AnimalWeightCAT_t, distcount_t> AWeightDistance;

    AWeightDistance AWeightDistanceCount;
    
    AnimalWeightCAT_t AnimalWeightCAT;
    distance_t dist;

    while (file >> AnimalWeightCAT >> dist) {
        ++AWeightDistanceCount[AnimalWeightCAT][dist];
    }

    for(AWeightDistance::iterator adit = AWeightDistanceCount.begin(); adit != AWeightDistanceCount.end(); ++adit) {
        std::cout << "AnimalWeightCAT: " << adit->first << "   count = " << adit->second.size() << '\n';
    }
    return 0;
}
运行结果
AnimalWeightCAT: 2   count = 4
AnimalWeightCAT: 3   count = 8
AnimalWeightCAT: 5   count = 6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:57:19