How to find the most common number in the input?

This is a very abstract explanation of what I am doing:

Say I have a text file full of numbers separated by newlines. Right now, I take these numbers and put them in map<int, int>, where the key is the number and the value is the frequency.

My ultimate goal is a list of numbers sorted by frequency. How can i do this? Note that the frequency can obviously appear more than once. The way I thought it was to do it struct, containing both the number and its frequency, and determine <that it never returned equality. Then I went through the map, placing all the elements in this structure, and then in the set.

+3
source share
3 answers

After you have built the frequency card, copy its pairs to std::vector<std::pair<int, int> >, and then the std::sortlast with the version std::sortwith 3-args, which takes the comparator as the third arg; as a comparator you can use one that compares the fields of .secondpairs first, and tags .first(if you want) only to eliminate the ambiguity of ordering pairs whose fields .secondare equal (but I don’t know, you think you really need the last bit, since you don’t care about ordering for cases with the same frequency, right?).

+8
source

If this is just an operation that you want to do yourself (and not a component that you want to use), the most practical way for me would be to do something like this:

sort <filename> | uniq -c | sed 's/^[ \t]*//' | sort -rn

, , , , .


EDIT: " ;" uniq " , , [] [item],

12
12
24
25
25
25

    2 12
    1 24
    3 25

sed ( , , , ), ( "n" , "r" ).

(, , , - ), "":

sort -t'\t' -k3 <filename> | ...

, , , .


2: ( )

cut -d'\t' -f4 <filename> | sort | uniq -c | sed 's/^[ \t]*//' | sort -rn
+1

std:pair std::map std::priority_queue. .

, .

0

Source: https://habr.com/ru/post/1763241/


All Articles