gpt4 book ai didi

c++ - 来自 std::map 的前 5 个值

转载 作者:行者123 更新时间:2023-11-27 23:10:37 25 4
gpt4 key购买 nike

我已经有一个函数可以取出具有最多映射值的键值。

// Function for finding the occurances of colors or in this case hex values
void findOccurrances(double * mostNumTimes, map<string, int> &hexmap, string * colorlist)
{
map<string,int>::iterator it = hexmap.begin();

for( ;it != hexmap.end(); it ++)
{
if(*mostNumTimes <= it->second)
{
*mostNumTimes = it->second;
*colorlist = it->first;
}
}
}

有没有一种简单的方法可以将其展开以显示前五个结果?我知道您可以将它复制到 vector ,但我想要一种更简单的方法。

最佳答案

复制到 vector 中并不难:

typedef std::pair<string, int> Pair;
std::vector<Pair> contents(hexmap.begin(), hexmap.end());

完成。

但要找到前5名,信不信由你<algorithm>有一个功能模板,可以完全满足您的需求。在 C++11 中,lambda 很有用:

std::vector<Pair> results(5);
std::partial_sort_copy(
hexmap.begin(), hexmap.end(),
results.begin(), results.end(),
[](const Pair &lhs, const Pair &rhs) { return lhs.second > rhs.second; }
);

results现在包含降序排列的前 5 个条目。

关于c++ - 来自 std::map 的前 5 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com