这个期中考试出的编程题目挺不错的 基础知识必须很牢固才能很轻松的通过 像我这样的渣渣 有两题很想了一会才通过。。。
#include <iostream>
#include <set>
using namespace std;
template <class T,class fun = less<T> ,class Alloc = allocator<T> >
class MySet:public set<T,fun,Alloc>
{
public:
set<T,fun,Alloc> my;
MySet(){}
MySet(T * first,T * last)
{
my.insert(first,last);
}
pair<class set<T>::iterator,class set<T>::iterator> FindInterval(T s,T e)
{
pair<class set<T>::iterator,class set<T>::iterator> tem;
tem.first = my.upper_bound(s);
tem.second = my.lower_bound(e) ;
return tem;
}
class set<T>::iterator begin()
{
return my.begin();
}
class set<T>::iterator end()
{
return my.end();
}
void insert(T d)
{
my.insert(d);
}
typename set<T>::iterator upper_bound(T a)
{
return my.upper_bound(a);
}
};
template<class T>
void MyPrint(T first,T last)
{
while(first != last)
{
cout<<*first<<" ";
++first;
}
}
int main()
{
int t;
cin >> t;
MySet<int> stInt;
int a[100];
while(t--) {
int n;
cin >> n;
for(int i = 0;i < n; ++i )
cin >> a[i];
MySet<int> stInt(a,a+n);
MyPrint(stInt.begin(),stInt.end()); //输出全部内容
cout << endl;
int s,e;
cin >> s >> e; // 后面要输出位于 s 和 e 之间的元素
pair<MySet<int>::iterator, MySet<int>::iterator> p;
p = stInt.FindInterval(s,e);
if( p.first != p.second) {
MyPrint(p.first,p.second);
cout << endl;
}
else
cout << "Interval Not Found" << endl;
cin >> n;
MySet<double,greater<double> > stDouble;
for( int i = 0;i < n; ++i) {
double d;
cin >> d;
stDouble.insert(d);
}
MyPrint(stDouble.begin(),stDouble.end());
cout << endl;
double w;
cin >> w;
cout << * stDouble.upper_bound(w) << endl;
}
}
greater 和less函数都是stl里面写好的 不用自己写 直接调用就可以了
开始自己写了 greater模板的实现 在调用的地方总是报错 可能是函数有冲突的原因吧。。
另外在 自己的类中申明set的时候要把所有的模板参数也送进去 要不然后面两个参数还是使用set的默认参数
这个 set前面必须加class或者typename才能编译通过。。。
pair<class set<T>::iterator,class set<T>::iterator> FindInterval(T s,T e)
{
pair<class set<T>::iterator,class set<T>::iterator> tem;
tem.first = my.upper_bound(s);
tem.second = my.lower_bound(e) ;
return tem;
}