[英]Most frequent element in a C++ List, STL?
I have a program, where I enter some numbers in a C++ STL list. 我有一个程序,可以在C ++ STL列表中输入一些数字。 I want to find the most frequent element of the list. 我想找到列表中最常出现的元素。 My question is what am I doing the wrong way, since the program does not work as expected? 我的问题是,由于程序无法按预期运行,我在做什么错误的方式?
// List.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
using namespace std;
char number;
int counter;
list <char> l;
vector <int> m;
list <char>::iterator START;
void countRepetition();
int main()
{
do {
number = getchar();
if (number != '0') {
l.push_back(number);
}
} while (number != '0');
/*for (START = l.begin(); START != l.end(); START++) {
m.push_back(countRepetition(*START));
}
for (int i = 0; i < m.size(); i++) {
cout << m[i] << endl;
}
*/
countRepetition();
auto x = max_element(m.begin(), m.end());
cout << *x << endl;
return 0;
}
void countRepetition() {
for (auto i = l.begin(); i != l.end(); i++) {
for (auto j = l.begin(); j != l.end(); j++) {
if (*i == *j) {
counter++;
}
m.push_back(counter);
}
}
}
I think what you want is something like: 我认为您想要的是这样的:
void countRepetition() {
for (auto i = l.begin(); i != l.end(); i++) {
int counter = 0;
for (auto j = l.begin(); j != l.end(); j++) {
if (*i == *j) {
counter++;
}
}
m.push_back(counter);
}
}
I would further advise to make m and l parameters to the function: void countRepetition(const list<char>& l, vector<int>& m)
我进一步建议对函数使用m和l参数: void countRepetition(const list<char>& l, vector<int>& m)
void countRepetition(const list<char>& l, vector<int>& m) {
for (auto i = l.begin(); i != l.end(); i++) {
int counter = 0;
for (auto j = l.begin(); j != l.end(); j++) {
if (*i == *j) {
counter++;
}
}
m.push_back(counter);
}
}
EDIT: (Thanks to papagaga) 编辑:(感谢papagaga)
With a map this can be solved even nicer: 使用地图可以更好地解决这个问题:
void countRepetition(const list<char>& l, map<char, int>& m) {
for(const auto& element : l){
++m[element];
}
}
Also you can use simple algorithm for_each + map container to calculate unique appearances. 您还可以使用简单的for_each +地图容器算法来计算唯一外观。
#include<iostream>
#include<list>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
list <char> Lst;
map<char,int16_t> MapCounter;
//Fill list by data
char Arr[] {1,1,2,3,4,5,6,7,4,2,1};
back_insert_iterator<decltype(Lst)> InsListIt(Lst);
copy(&Arr[0], &Arr[12], InsListIt);
//Calc unique appearance of elements. Store results in MapCounter of all unique elements apperances
for_each(Lst.begin(), Lst.end(), [&MapCounter](int val){ MapCounter[val]++; });
//Calc element that appears max frequeantly times in list
char MaxElement = 0;
int16_t MaxRepeat = 0;
for_each(MapCounter.begin(), MapCounter.end(), [&MaxElement, &MaxRepeat](pair<char, int16_t> el)
{
if ( MaxRepeat < el.second )
{
MaxElement = el.first;
MaxRepeat = el.second;
}
});
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.