Question: I have a vector with integers. I would like to select the most common numbers. I would like to make a top 5 list. For example:

```
std::vector<int> numbers = {32, 32, 32, 12, 12, 11, 11, 11, 9};

```

the most common numbers are: TOP 1: 32, TOP 2: 11, TOP 3: 12, TOP 4: 9;

after I selected them, I would like to store it into an other vector: the most common numbers.

Answer: 
you can do this: create a set so you get rid off duplicated, then find the frequency of every item of the set in the vector, with this result create a pair (something like int, int) push the pair in a vector and finally sort it using your own predicate:  

now for the top x you can do a for loop or just resize the vector if you are sure what the consequences of this are.

```
std::vector<int> numbers{32, 32, 32, 12, 12, 11, 11, 11, 9};
std::set<int> mySet(numbers.begin(), numbers.end());
std::vector<std::pair<int, int>> result{};

for(const auto& x : mySet)
{
    result.push_back(std::make_pair(x , std::count(numbers.begin(), numbers.end(), x)));
}
std::sort(result.begin(), result.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b){return (b.second < a.second);});
//result.resize(3);
std::cout << "Top: " << std::endl;
for(const auto& x : result)
{
   std::cout << x.first << ':' << x.second << std::endl;
}

```

the result will be:

> 
> Top: 11:3 32:3 12:2 9:1
> 
> 
>
There are many many ways how to achieve this. One of which may be.

```
std::vector numbers = {32, 32, 32, 12, 12, 11, 11, 11, 9};
int maxNumber = *std::max_element(numbers.begin(), numbers.end())
std::vector<int> occurrences(maxNumber + 1, 0);
for(auto& value : numbers)
{
   occurrences[value]++;
}

```

Then you just need to sort the array whilst keeping track of the indexes. This is a topic of another question [C++ sorting and keeping track of indexes](https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes).