-1

Given a non-empty array of numbers. Display the number of the most common in this array.

#include <iostream>
    #include <map>
    #include <algorithm>
    #include <clocale>
    #include <iterator>

    int main()
    {
        setlocale(LC_ALL, "");
        const int size = 5;
        int array[size];
        for (int i = 0; i < size; i++)
            std::cin >> array[i];
        std::map<int, int> map;
        for (int i = 0; i < size; i++)
            map[array[i]] = std::count(std::begin(array), std::end(array), array[i]);
        std::cout<< "The most common element: " << map.begin()->first << std::endl;
        std::sort(std::begin(array), std::end(array));
        std::cout << "Sorting array: \n";
        std::copy(std::begin(array), std::end(array), std::ostream_iterator<int>(std::cout, " "));
        std::cout<< std::endl;

    }

Can I rewrite such program in case two-dimensional array? And how i can it do?

1 Answers1

0

Your original program doesn't work, it just prints the lowest number in your input, since std::map sorts by key, you use array[i] as keys for your map, and you simply print the key(.first) of the first element(.begin()) in the map.

To convert the code to 2 dimensions, use a std::pair<int,int> as your key instead of a single int. So your map would become:

std::map<std::pair<int,int>,int> map;

In your original code you're calling std::count for every element. That's not necessary, you can simply increase the map-element for that particular value. Assuming you have a two-dimensional array of values, use the following to count how many times each value occur:

int array[SIZE][2];
...
for (i=...) {
    ++map[std::make_pair(array[i][0],array[i][1])];
}

Then you can use std::max_element with a compare-function comparing the second element (the count) of the container element to find the most common element. A special compare-function is needed because the value_type of a std::map is a std::pair<K,V> where K and V are Key and Value respectively.

Kleist
  • 7,785
  • 1
  • 26
  • 30