【发布时间】:2012-06-10 10:17:16
【问题描述】:
我有一个大型(ish - >100K)集合,将用户标识符(一个 int)映射到他们购买的不同产品的数量(也是一个 int)。我需要像重新组织数据一样高效可以找出有多少用户拥有不同数量的产品。例如,有多少用户拥有一种产品,有多少用户拥有两种产品等。
我通过将原始数据从 std::map 反转为 std::multimap 来实现这一点(其中键和值只是颠倒了。)然后我可以挑选出拥有 N的用户数量> 使用 count(N) 的产品(尽管我也将值唯一地存储在一个集合中,因此我可以确定我正在迭代的值的确切数量及其顺序)
代码如下:
// uc is a std::map<int, int> containing the original
// mapping of user identifier to the count of different
// products that they've bought.
std::set<int> uniqueCounts;
std::multimap<int, int> cu; // This maps count to user.
for ( map<int, int>::const_iterator it = uc.begin();
it != uc.end(); ++it )
{
cu.insert( std::pair<int, int>( it->second, it->first ) );
uniqueCounts.insert( it->second );
}
// Now write this out
for ( std::set<int>::const_iterator it = uniqueCounts.begin();
it != uniqueCounts.end(); ++it )
{
std::cout << "==> There are "
<< cu.count( *it ) << " users that have bought "
<< *it << " products(s)" << std::endl;
}
我不禁觉得这不是最有效的方法。有人知道这样做的聪明方法吗?
我的限制是 我不能使用 Boost 或 C++11 来做到这一点。
哦,还有,如果有人想知道,这既不是作业,也不是面试问题。
【问题讨论】: