今天继续学习类模板和函数模板。
有几个新的认识:
1。不止可以有一个模板,一个template里面可以有不止一个T,可以有几个,但是要不同名字。
2。注意在声明时候要写typename。
3。用迭代器的一个技巧,类型用一个T, iterator用一个Iter。声明两个类模板。
贴程序:
查找任意容器中出现某个元素:
#include<iostream>
#include<vector>
using namespace std;
template <typename T,typename iter>
iter findd (T a,iter t1,iter t2)
{ while(t1!=t2)
{ if(*t1==a) return t1;
else t1++;
}
return t2;
}
int main()
{
vector<int> ivec;
ivec.push_back(1);
ivec.push_back(2);
ivec.push_back(3);
vector<int>::iterator b=ivec.begin();
vector<int>::iterator c=ivec.end();
int x(5);
if(findd(x,b,c)!=ivec.end()) cout<<"find it!"<<endl;
else cout<<"no!"<<endl;
return 0;
}
传递迭代器参数:统计出现最频繁的元素
#include<iostream>
using namespace std;
template<typename T>
typename T::value_tpye most(T first,T last)
{ allocator<typename T::value_type> alloc;
T newfirst=alloc.allocate(last-first);
T newlast=newfirst+(last-first);
std::unitialized_copy(first,last,newfirst); 运行到这里有问题!
std::sort(newfirst,newlast); 注意排序
std::size_t maxocc=0,occ=0; 记录数目
T preiter=newfirst,maxoccelem=newfirst;
while(newfirst != newlast)
{
if(*newfirst!=*preiter)
{if(occ>maxocc) maxocc=occ;
maxoccelem=preiter;
}
return *maxoccelem;
}
if(occ>maxocc)
{
maxocc=occ;
maxoccelem=preiter;
}
return *maxoccelem;
}
int main()
{int a[]={1,2,3,3,3,2,1};
vector<int> ivec(a,a+7);
vector<int>::iterator a,b;
a=ivec.begin();b=ivec.end();
cout<<most(a,b)<<endl;
return 0;
}
打印元素:两种:一用迭代器,二用size_type
#include<iostream>
#include<vector>
using namespace std;
/*template <typename cc,typename T>
void print(T t1,T t2)
{typename cc::size_type index=0;
while(index!=t2-t1)
{cout<<*t1<<" ";
t1++;
}
while(t1!=t2){
cout<<*t1<<" ";
t1++;
}
}
*/
template <typename T>
void print(const T& t)
{typename T::size_type index=0;
while(index!=t.size())
{cout<<t[index]<<" ";
index++;
}
}
int main()
{
int a[]={1,2,3,4,5,6,7};
vector<int> ivec(a,a+7);
vector<int>::iterator b,c;
b=ivec.begin();c=ivec.end();
//print(b,c);
print(ivec);
return 0;
}