C/C++

Написать программу С++

В данном массиве найти максимальное количество одинаковых элементов.

Т. е., я задаю массив, а программа должна выдать макс количество элементов. Только пожалуйста, пропишите программу полностью, от и до.
Salo Kum
Salo Kum
130
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
int N;
do
{
cout << "Введите N: ";
cin >> N;
} while(N <= 0);
int * A = new int[N];

srand(time(NULL));
for(int x = 0; x < N; x++)
{
A[x] = rand() % 10 + 1;
cout << A[x] << ' ';
}
cout << endl << endl;

int count = 0, count_max = 0;
for(int x = 0; x < N; x++)
{
count = 0;
for(int y = 0; y < N; y++)
{
if(A[x] == A[y]) count++;
}
if(count > count_max)
{
count_max = count;
}
}

cout << "Максимальное количество одинаковых элементов -- " << count_max
<< " штук." << endl;

if(A == NULL) return 1;
delete [] A;
A = NULL;
return 0;
}
Федор Давидюк
Федор Давидюк
50 066
Лучший ответ
Salo Kum и снова благодарю!
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <map>
#include <random>
#include <iterator>
using namespace std;
unsigned frequent(const int* box, const size_t length) {
using cref_t = const pair<int, unsigned>&;
const auto comp = [](cref_t a, cref_t b) { return a.second < b.second; };
map<int, unsigned> tmp;
for (auto i = 0U; i < length; ++i) ++tmp[box[i]];
auto pos = max_element(tmp.begin(), tmp.end(), comp);
return pos->first;
}
int main() {
uniform_int_distribution<> uid(1, 9);
mt19937 gen{ random_device()() };
const auto rand = [&](int& x) { x = uid(gen); };
cout << "Length: ";
size_t length;
cin >> length;
auto box = new int[length];
for_each(box, box + length, rand);
copy(box, box + length, ostream_iterator<int>(cout, " "));
puts("");
auto target = frequent(box, length);
cout << "Frequent: " << target << '\n';
delete[] box;
system("pause > nul");
}
#include < iostream >
#include < algorithm >
#include < vector >

using namespace std;

int find(vector& array)
{
vector qarr = array;
sort(qarr.begin(), qarr.end());
int count = 0, tmp = qarr[0]-1, max_count=0;
for (int& i : qarr)
if (i == tmp) count++; else
{
if (max_count < count) max_count = count;
count = 1;
tmp = i;
}
return max(count, max_count);
}

int main()
{
int size;
cin >> size;
vector array(size);
for (int& i : array) i = rand() % 31 - 15;
for (int& i : array) cout << i << " ";
puts("");
cout << find(array);
}