从容器中获取前5个算法?

cel*_*lta 2 c++ sorting algorithm

我有一个类(对象),User.该用户有2个私有属性,"名称"和"受欢迎程度".我将对象存储到向量(容器)中.

从容器中,我需要找到前5位最受欢迎的用户,我该怎么做?(我有一个丑陋的代码,我会在这里发布,如果你有更好的方法,请告诉我.如果你认为矢量不是一个好的选择,请随意使用其他容器,但请仅使用:map或multimap,列表,向量或数组,因为我只知道如何使用它们.)我目前的代码是:

int top5 = 0, top4 = 0, top3 = 0, top2 = 0, top1 = 0;
vector<User>::iterator it;

for (it = user.begin(); it != user.end(); ++it) 
{
    if( it->getPopularity() > top5){
        if(it->getPopularity() > top4){
            if(it->getPopularity() > top3){
                if(it->getPopularity() > top2){
                    if(it->getPopularity() > top1){
                        top1 = it->getPopularity();
                        continue;
                    } else {
                        top2 = it->getPopularity();
                        continue;
                    }
                } else {
                    top3 = it->getPopularity();
                    continue;
                }
            }
        } else {
            top4 = it->getPopularity();
            continue;
        }
    } else {
        top5 = it->getPopularity();
        continue;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道代码很难看并且可能容易出错,因此如果你有更好的代码,请与我们分享(us == cpp newbie).谢谢

Fre*_*abe 9

您可以使用该std::partial_sort算法对矢量进行排序,以便对前五个元素进行排序,其余元素保持未排序.像这样的东西(未经测试的代码):

bool compareByPopularity( User a, User b ) {
    return a.GetPopularity() > b.GetPopularity();
}

vector<Users> getMostPopularUsers( const vector<User> &users, int num ) {
    if ( users.size() <= num ) {
        sort( users.begin(), users.end(), compareByPopularity );
    } else {
        partial_sort( users.begin(), users.begin() + num, users.end(), 
                      compareByPopularity );
    }
    return vector<Users>( users.begin(), users.begin() + num );
}
Run Code Online (Sandbox Code Playgroud)

  • @celta:对于像你这样的矢量大小(10000-40000),任何性能差异可能都是微不足道的(免责声明:我没有对其进行分析).但是,我认为`partial_sort`在道德方面是优越的:它更清楚地表达了代码的意图(至少对我来说,你的里程可能会有所不同). (2认同)