如何在C++中对CSV用户ID执行Groupby(count)并按好友数降序排序
在C++中实现CSV数据的GroupBy统计与排序
我来帮你搞定这个需求!要在C++里处理CSV的分组统计和排序,其实分几步就能实现,我给你详细拆解一下:
整体思路
- 读取并解析CSV:逐行读取文件内容,提取每一行的用户ID和好友ID
- 统计好友数量:用哈希表(
unordered_map)记录每个用户ID对应的好友数,每读到一条记录就给对应ID的计数加1 - 排序统计结果:把哈希表中的数据转成可排序的容器(比如
vector),然后按照好友数量降序排列(数量相同时按用户ID升序保持一致性) - 输出结果:按照你需要的格式输出排序后的统计数据
完整实现代码
#include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include <vector> #include <algorithm> #include <string> using namespace std; int main() { // 1. 打开CSV文件 ifstream csvFile("friends.csv"); if (!csvFile.is_open()) { cerr << "无法打开文件!" << endl; return 1; } string line; unordered_map<string, int> friendCountMap; // 跳过表头行 getline(csvFile, line); // 2. 逐行读取并统计 while (getline(csvFile, line)) { stringstream ss(line); string userId, friendId; // 拆分每行的两个字段(用逗号分隔) getline(ss, userId, ','); getline(ss, friendId, ','); // 给当前用户的好友计数加1 friendCountMap[userId]++; } csvFile.close(); // 3. 将哈希表数据转为vector以便排序 vector<pair<string, int>> sortedList(friendCountMap.begin(), friendCountMap.end()); // 自定义排序规则:按好友数量降序,数量相同则按用户ID升序 sort(sortedList.begin(), sortedList.end(), [](const pair<string, int>& a, const pair<string, int>& b) { if (a.second != b.second) { return a.second > b.second; } return a.first < b.first; }); // 4. 输出结果 cout << "ID,Friend_count" << endl; for (const auto& entry : sortedList) { cout << entry.first << "," << entry.second << endl; } return 0; }
代码细节说明
- 文件读取:用
ifstream打开文件,先跳过第一行表头,避免统计表头内容 - 哈希表统计:
unordered_map<string, int>的键是用户ID,值是好友数量,每次读取到用户ID就自动累加计数(如果是新ID会默认初始化为0再加1) - 排序逻辑:因为
unordered_map是无序的,所以我们把它的键值对转成vector,然后用sort函数配合lambda表达式实现自定义排序——优先按好友数量降序,数量相同时按用户ID升序排列(和你给出的示例结果一致) - 输出格式:严格按照你期望的CSV格式输出表头和统计结果
运行结果
运行这段代码后,会输出你想要的结果:
ID,Friend_count
P0,3
P1,3
P3,2
P2,1
内容的提问来源于stack exchange,提问作者Hossein
相关产品推荐
相关产品推荐

