我有一个程序,我在C ++ STL列表中输入一些数字。我想找到列表中最常见的元素。我的问题是我做错了什么,因为程序没有按预期工作?
// 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);
}
}
}
答案 0 :(得分:2)
我认为你想要的是:
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);
}
}
我会进一步建议为函数制作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);
}
}
编辑:(感谢papagaga)
使用地图可以更好地解决这个问题:
void countRepetition(const list<char>& l, map<char, int>& m) {
for(const auto& element : l){
++m[element];
}
}
答案 1 :(得分:1)
您也可以使用简单算法for_each + map container来计算独特的外观。
#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;
}