工作中,有时候需要对相同的条件进行分类,比如同名的,同年龄的。
添加头文件
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
定义结构体
struct Persion
{
int iAge;
std::string strName;
std::string strAddr;
static void print(const Persion& p)
{
std::cout << "iAge:" << p.iAge
<< ",strName" << p.strName
<< ",strAddr:" << p.strAddr << std::endl;
}
};
实现:
template<class Fn, class Type>
std::unordered_multimap<typename std::result_of<Fn(Type)>::type, Type>
GroupBy(const std::vector<Type>& vcPersions, Fn&& func)
{
using KeyType = typename std::result_of<Fn(Type)>::type;
std::unordered_multimap<KeyType, Type> mapPersions;
for (const auto& persion : vcPersions)
{
mapPersions.insert({ func(persion),persion });
}
return mapPersions;
}
实现思想是根据lambda表达式的返回值作为map的key,因为multimap这个容器允许相同的key存在多个,所以自动就实现了分组
例子:
void TestResultOf()
{
std::vector<Persion> persions = { {1,"liu","shenzhen"},{2,"liu","guangzhou"},{1,"cai","guangzhou"} };
auto result = GroupBy(persions, [](const Persion& persion) {
return persion.strName;//iAge,strName,strAddr
});
for (const auto& p : result)
{
Persion::print(p.second);
}
}