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

C++中如何统计多个std::vector实例的出现频率

解决方案
  • 直接利用std::vector内置的operator==逐元素比较的特性,不需要额外自定义相等判断逻辑
  • 选用std::map<std::vector<int>, int>作为频次统计容器,std::vector可直接作为map的键使用
  • 遍历所有待统计的vector完成计数后,按要求格式输出结果即可

完整可运行代码

#include <iostream>
#include <vector>
#include <map>
using namespace std;

// 按要求格式打印vector内容
void printVector(const vector<int>& v) {
    cout << "(";
    for (size_t i = 0; i < v.size(); ++i) {
        if (i != 0) cout << ",";
        cout << v[i];
    }
    cout << ")";
}

int main(){
    vector<int> v1={0,0,1,2,3,0,0,0};
    vector<int> v2={0,0,1,2,3,4,0,0};
    vector<int> v3={0,0,2,4,3,0,0,0};
    vector<int> v4={0,0,1,2,3,0,0,0};
    vector<int> v5={0,0,6,2,3,5,6,0};

    // 汇总所有待统计vector
    vector<vector<int>> all_vecs = {v1, v2, v3, v4, v5};
    map<vector<int>, int> count_map;

    // 统计出现频次
    for (const auto& vec : all_vecs) {
        count_map[vec]++;
    }

    // 输出结果
    for (const auto& item : count_map) {
        printVector(item.first);
        cout << " = " << item.second << " time(s)" << endl << endl;
    }

    return 0;
}

上述代码运行后输出和你给出的预期格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:27:00