sorting a map by converting it to vector I have a map that I want to print out sorted by value, I convert it to vector and sort the vector. Is this code correct?

#include &lt;map&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
#include &lt;utility&gt;
int main()
{
    std::map&lt;char, int&gt; freq;
    std::string text;
    std::getline(std::cin, text);
    std::vector&lt;std::pair&lt;char, int&gt;&gt; items;
    for(auto &amp; ch: text)
            freq[ch]++;

    for(auto [key, value]: freq)
        items.push_back(std::make_pair(key, value));

    std::sort(items.begin(), items.end(),

              [](auto a, auto b)
                { return a.second &gt; b.second;});     

    for(auto [key, value]: items)
       std::cout &lt;&lt; key &lt;&lt; " " &lt;&lt; value &lt;&lt; std::endl;
    return 0;   

}
The code is correct. However, I still have some recommendations:


Sort the includes, so you can easily spot recurring/missed ones

#include &lt;algorithm&gt;
#include &lt;iostream&gt;
#include &lt;map&gt;
#include &lt;utility&gt;
#include &lt;vector&gt;

You do not need to run the loop, you can simply pass the map to the std::vector constructor. As you use structured bindings and therewith at least C++17, I suggest Template Argument Deduction to omit the type of the vector

std::vector items(freq.begin(), freq.end());

The comparison function takes the arguments by copy, which is not optimal. Rather use const auto&amp;:

[] (const auto&amp; a, const auto&amp; b) { return a.second &gt; b.second;})

Note that std::sort may change the ordering of elements with equal value. If you want those elements with equal frequency to appear in the same order than in the map you would need std::stable_sort. However, keep in mind that this requires additional resources in memory and compute time.
You are using a std::map, which is an ordered container. If you are only interested in the frequencies then a std::unordered_map will generally offer better performance. Although for a simple alphabet this will most likely be negligible.