Frequency of Numbers in a 1D Array

前端 未结 6 420
清酒与你
清酒与你 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:14

    You never seem to update the counters. Try this:

    int array[8] = {6,1,7,8,6,6,1,9};
    
    unsigned int store[10] = {};    // large enough to hold the largest array value,
                                    // initialized to zero
    
    for (int n : array) ++store[n]; // update counts
    
    for (int i = 0; i != 10; ++i)
    {
        std::cout << "Frequency of int " << i << " is " << store[i] << "\n";
    }
    

    If the set of values that occur is sparse, or includes negatives, or simply does not fit into a dense range of integers nicely, you can replace unsigned int[10] with an associative container, e.g.:

    std::map store;
    
    // algorithm as before
    
    for (auto const & p : store)
    {
        std::cout << "Frequency of " << p.first << " is " << p.second << "\n";
    }
    

提交回复
热议问题