练习使用模板

练习使用模板,自己编写《C++ Primer》上一道课后习题:

题目:编写一个函数模板,接受表示未知类型迭代器的一对值,找出在序列中出现得最频繁的值。

#include <iostream>

#include <vector>

#include <string>

#include <set>

#include <algorithm>

#include <utility>

using namespace std;

template<typename T>

int Count(set< pair<T,int> > st,T val)

{

    set< pair<T,int> >::iterator it = st.begin();

    while (it != st.end())

    {

       if (*it->first == *val)

       {

           return 1;

       }

       ++it;

    }

    return 0;

}

template<typename T>

set< pair<T,int> >::iterator Find(set< pair<T,int> > &st, const T& val)

{

   set< pair<T,int> >::iterator it = st.begin();

    while (it != st.end())

    {

       if (*it->first == *val)

       {

           return it;

       }

       ++it;

    }

    return st.end();

}

template<typename T>

T frequent(T first,T end)

{

   set< pair<T,int> >    st;

   while(first != end)

   {

     if (!Count(st,first))

     {

       int ct = 1;

       pair<T,int> p(first,ct);

       st.insert(p);

     }

     else

     {

       set< pair<T,int> >::iterator it = Find(st,first);

       it->second += 1;

     }

      ++first;

   }

   set< pair<T,int> >::iterator it1 = st.begin(),it2 = it1;

   while(it1 != st.end())

   {

    if (it1->second > it2->second)

    {

       it2 = it1;

    }

    ++it1;

   }

   return it2->first;

}

int main()

{

    int a[] = {4,3,2,2,2,3,};

    vector<int> vec(a,a+6);

    vector<int>::iterator it = frequent(vec.begin(),vec.end());

    cout << "数字出现最频繁的是: " << *it << endl;

    string str[] = {"hello","world","world","love","love","love","you"};

    vector<string> strval(str,str+7);

    vector<string>::iterator st = frequent(strval.begin(),strval.end());

    cout << "字符串出现最频繁的是: " << *st << endl;

    return 0;

}

 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值