除了对整个方法进行编码之外,我可以使用C++中的内置函数来查找数组中出现次数最多的元素吗



我有一个数组v = [5,1,5,4,5,2,3,4,5,6,5]。我想返回最频繁出现的值,在本例中为5。C++中是否有一个内置函数用于相同的功能?

我可以实现一种方法来计算每个元素的频率,从而返回具有最大频率的值,但我非常想知道是否有更好的方法。

您可以使用带有std::max_element函数的std::unordered_map容器来查找数组或向量中最频繁的元素。例如:

int getMostFrequentElement(vector<int> &arr)
{
if (arr.empty())
return -1;
unordered_map<int, int> freq_count;
for (const auto &item : arr)
freq_count[item]++;

auto most_freq_int =
std::max_element(freq_count.begin(), freq_count.end(),
[] (const auto &x, const auto &y) {return x.second < y.second;});
return most_freq_int->first;
}

最新更新