Другие языки программирования и технологии

Составить программу С++ В массиве целых чисел с количеством элементов n найти наиболее часто встречающееся число

#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int a[] = { 1, 4, 5, 4, 1, 4 };
const auto n = sizeof(a) / sizeof(a[0]);
set<int> u;
for (const auto v : a) if (!u.count(v)) u.insert(v);
auto c = 0, y = 0;
for (const auto e : u) {
const auto x = count(a, a + n, e);
if (x > c) {
c = x;
y = e;
}
}
cout << " " << y << " : " << c << endl;
cin.get();
}
// пример с использованием сортировкой. Говорят, меньше памяти жрет, чем иной способ.

#include "iostream"
#include "algorithm"
#include "vector"

int main()
{
srand(NULL);
setlocale(LC_ALL, "Russian");

int n;

std::wcout << L"Введите кол-во чисел: ";
std::cin >> n;
//n = rand() % 9999 + 1;

std::vector arr;

std::wcout << L"Введите числа:" << std::endl;

for (int i = 0; i < n; i++)
{
int value;
//std::cin >> value;
value = rand() % 10;
arr.push_back(value);
}

std::wcout << L"Элементы массива:";
for (auto it = arr.begin(); arr.end() != it; ++it)
{
std::cout << " " << *it;
}

std::wcout << std::endl << L"Сортируется массив" << std::endl;

sort(arr.begin(), arr.end());

std::wcout << L"Отсортированный массив:";

// У нас всегда есть одно число, оно будет первым для сравнения
int max_counter = 1;
int most_popular_number = *arr.begin();
int current_counter = 1;
int current_number = *arr.begin();

for (auto it = arr.begin(); arr.end() != it; ++it)
{
if (current_number != *it)
{
current_counter = 1;
current_number = *it;
}
else if (++current_counter > max_counter)
{
if (most_popular_number != current_number)
{
most_popular_number = current_number;
}

max_counter = current_counter;
}
}

std::wcout << std::endl << L"Наиболее встречающееся число: " << most_popular_number << std::endl;

system("pause");
}

Похожие вопросы