不知道错在哪里
要求如下
Exercise
16.12:
Write a function template that takes a pair of values that represent iterators of unknown type.
Find the value that occurs most frequently in the sequence.
编写一个函数模板,接受表示未知类型迭代器的一对值,找出在序列中出现得最频繁的值。
#include <iostream>
#include <vector>
#include <map>
using namespace std;
template<typename T, typename CT>
void countfrenquency(T &first, T &last)
{
map<CT, int> ctmap;
typename map<CT, int>::iterator ctiit;
int sum = 0;
CT max;
for (T t = first; t != last; t++)
{
if (!ctmap.find(*t))
{
ctmap.insert(*t);
}
else
{
ctmap[*t]++;
}
}
ctiit = ctmap.begin();
while (ctiit != ctmap.end())
{
if ((*ctiit) > sum)
{
sum = ctmap[*ctiit];
max = *ctiit;
}
}
cout << max << endl;
}
int main()
{
std::cout << "Hello World!\n";
vector<int> iv({ 1,1,2,3,4,6 });
typedef vector<int>::iterator ivit;
countfrenquency<ivit &, int &>(iv.begin(), iv.end());
}
报错提示:
求解!
给你一个新代码!望采纳!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
template <typename T>
typename T mosFre(T first,T last)
{
sort(first,last);
size_t maxOccu = 0,occu = 0;
T preIter = first,maxOccuElemIt = first;
while(first != last)
{
if(*first != *preIter)
{
if(occu >maxOccu)
{
maxOccu = occu;
maxOccuElemIt = preIter;
}
occu = 0;
}
++occu;
preIter = first;
++first;
}
//occur count of the last value compare to the current maxcount
if(occu > maxOccu)
{
maxOccu = occu;
maxOccuElemIt = preIter;
}
return maxOccuElemIt;
}
int main()
{
int ia[] = {2,2,3,3,3,6};
vector <int> ivec(ia,ia+sizeof(ia)/sizeof(int));
cout <<*mosFre(ivec.begin(),ivec.end())<<endl;
system("pause");
return 0;
}