Frequency of Numbers in a 1D Array

前端 未结 6 563
清酒与你
清酒与你 2021-01-27 03:54

its been 6 hours since I have been writing the code but to no avail, I don\'t no where I am making the mistake but I am making some. Its a frequency output program and output sh

6条回答
  •  梦谈多话
    2021-01-27 04:04

    You may use a map first to store num->frequency and then a multimap to store freqeuncy => num.

    Here is the working solution.

    #include 
    #include 
    #include 
    
    int main()
    {
        int array[8] = {6,1,7,8,6,6,1,9};
    
        // A map to store num => freq 
        std::map  freq;
    
        // A map to store freq(can be duplicate) => num 
        std::multimap  freqCounts;
    
        // Store num => frequency
        for (int i = 0 ; i < 8; i++)
        {
            freq[array[i]] += 1;
        }
    
        // Now Store freq => num
        for(auto const & iter : freq)
        {
            freqCounts.insert (std::pair(iter.second, iter.first)); 
        }
    
        // Print in reverse order i.e. highest frequency first
        for (std::multimap::reverse_iterator rit=freqCounts.rbegin(); rit!=freqCounts.rend(); ++rit)
        {
            std::cout << rit->second << " : " << rit->first << '\n';
        }
        return 0;
    }
    

提交回复
热议问题