大佬教程收集整理的这篇文章主要介绍了重新排序基于C地图的集合的有效方法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我通过将原始数据从std :: map转换为std :: multimap(其中键和值被简单地反转)来实现这一点.然后,我可以使用COunt(N)选择具有N个产品的用户数量(虽然我也将值唯一存储在一个集合中,@R_518_9447@确定我迭代的值的确切数量及其顺序)
代码如下所示:
// 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来做到这一点.
哦,如果有人想知道,这既不是家庭作业,也不是面试问题.
它还可以减少地图上的查找开销,获得内存局部性的好处,并使用向量的恒定时间查找替换调用以计算多图(这不是常量时间操作).
所以你可以这样做:
std::vector< int > uniqueCounts( MAX_PRODUCTS_PER_USER ); for ( map<int,int>::const_iterator it = uc.begin(); it != uc.end(); ++it ) { uniqueCounts[ uc.second ]++; } // Now write this out for ( int i = 0,std::vector< int >::const_iterator it = uniqueCounts.begin(); it != uniqueCounts.end(); ++it,++i ) { std::cout << "==> There are " << *it << " users that have bought " << i << " products(s)" << std::endl; }
即使您不知道产品的最大数量,您似乎可以猜测最大值并根据需要调整此代码以增加矢量的大小.无论如何,它肯定会导致比原始示例更少的分配.
所有这些都假设您在处理完这些数据之后实际上并不需要用户ID(并且如下面的评论所指出的那样,为每个用户购买的产品数量是一个相对较小且相邻的集合.否则你可能最好使用地图代替矢量 – 你仍然会避免@L_364_21@multimap :: count函数,但可能会失去一些其他好处)
以上是大佬教程为你收集整理的重新排序基于C地图的集合的有效方法全部内容,希望文章能够帮你解决重新排序基于C地图的集合的有效方法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。