Return enum with most occurrences

If I have an array of structs that contain an enum of type Fruit, how can I write a function using modern practices/features to return the type of Fruit that occurs the most?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
enum class Fruit
{
    Apple,
    Banana,
    Mango
};

struct Container
{
    Fruit fruit;
};

Fruit highestCountFruit(Container containers[], std::size_t size)
{
    // ...
}

int main()
{
    Container containers[4];
    containers[0].fruit = Fruit::Apple;
    containers[2].fruit = Fruit::Apple;
    containers[3].fruit = Fruit::Banana;
    containers[4].fruit = Fruit::Mango;

    Fruit fruit = highestCountFruit(containers, 4);
}


This is purely just curiousity, I can implement a naive solution with a for loop, a few counting variables and an if statement but I'm sure there would be some sort of modern STL solution.. I don't even know where to start with a more advanced solution as I'm only starting to learn the STL.

Even just pointing me in the right direction would be appreciated.

Last edited on
Following the KISS principle I would copy the values into a std::map and then use std::max_element with a lambda.
Topic archived. No new replies allowed.