程序设计实习 第二十一讲 习题课

57
程程程程程程 程程程 程程程

Upload: colin-rhodes

Post on 01-Jan-2016

172 views

Category:

Documents


0 download

DESCRIPTION

程序设计实习 第二十一讲 习题课. 类和对象基本概念 (1). 写出下面程序的运行结果 class Apple { private : static int nTotalNumber; public: Apple() { nTotalNumber ++; } ~Apple( ) { nTotalNumber --; } static void PrintTotal() { cout

TRANSCRIPT

程序设计实习

第二十一讲 习题课

北京大学《程序设计实习》课程

类和对象基本概念 (1)

写出下面程序的运行结果 class Apple {

private :static int nTotalNumber;

public:Apple(){ nTotalNumber ++; }~Apple( ) { nTotalNumber --; }static void PrintTotal() { cout << nTotalNumber << endl; }

};int Apple::nTotalNumber = 0; Apple Fun( const Apple & a ) { a.PrintTotal(); return a ; }int main () {

Apple * p = new Apple[4];Fun( p[2]); Apple p1, p2;delete [] p;p1.PrintTotal();

}

解析: return 返回时,产生临时变量, Total Number 析构时会减小 41

北京大学《程序设计实习》课程

类和对象基本概念 (2)

* 写出下面程序的运行结果 class Sample{public:

int v;Sample() { };Sample(int n):v(n) { };Sample( Sample & x) { v = 2 + x.v ; }

};Sample PrintAndDouble( Sample o){ cout << o.v <<endl; o.v = 2 * o.v;

return o;}int main(){

Sample a(5);Sample b = a;Sample c = PrintAndDouble( b );cout << c.v << endl;Sample d;d = a;cout << d.v ;

}

解析:构造函数和复制构造函数的调用9225 注意区分:Sample b=a; d=a;

(vc2008 实际运行结果为 20)

北京大学《程序设计实习》课程

类和对象基本概念 (3)

程序输出结果如下,请填空05class A {public:

int val;A(____________ ){ val = n; }; ___________ GetObj() {

return ________; }

};main() { A a; cout <<a.val << endl;

a.GetObj() = 5;cout << a.val << endl;

}

A(int n=0) A& GetObj(){ return *this;}或者int& GetObj(){ return val;}

北京大学《程序设计实习》课程

类和对象基本概念 (4) 程序输出结果如下,请填空

3+4i 5+6i补足 Complex 类的成员函数,不能增加成员变量class Complex {private:

double r,i;public:

void Print() {cout << r << "+" << i << "i" << endl;}};int main(){ Complex a;

a = "3+4i"; a.Print();a = "5+6i"; a.Print();

}

北京大学《程序设计实习》课程

类和对象基本概念 (4)

构造函数Complex() {};Complex (const char t[]){

if(!t){ r=0.0; i=0.0; }else{

r = t[0] - '0'; i = t[2] - '0'; } }

另一种思路重载赋值操作符Complex &operator=(const

char t[]){ if(!t)

{ r=0.0; i=0.0; } else {

r = t[0] - '0'; i = t[2] - '0'; } return *this;}

北京大学《程序设计实习》课程

类和对象基本概念 (5)

程序输出结果如下,请填空10补足 Sample 类的成员函数,不能增加成员变

量class Sample{public:

int v;Sample(int n):v(n) { };

};main(){ Sample a(5);

Sample b = a;cout << b.v ;

}Sample( Sample & x) { v = 2 * x.v ; }

北京大学《程序设计实习》课程

类和对象基本概念 (6)

程序输出结果如下,请填空ThisHello补足 MyString 类的成员函数,不能增加成员变量class MyString{

char * p;public:

MyString( char * s ) {p = new char[strlen(s)+1];strcpy(p,s);

}~MyString() { delete [] p;} const char * c_str() { return p;}

};

main(){MyString

s1("This"), s2 =s1;s2.Copy ( "Hello");cout << s1.c_str ()

<< endl << s2.c_str () ;}

北京大学《程序设计实习》课程

类和对象基本概念 (6)

补足成员函数void Copy( char * s) {

delete [] p;p = new char[strlen(s)+1];strcpy(p,s);

}

MyString( MyString & o ) {p = new char[strlen(o.p ) + 1 ];strcpy( p, o.p);

}

北京大学《程序设计实习》课程

类和对象基本概念 (7)

程序输出结果如下,请填空5,55,5class Base {public:

int k;Base (int n) : k(n) { }

};class Big{public:

int v;Base b;Big _____________ { }Big _____________ { }

};

main(){Big a1(5);Big a2 = a1;cout << a1.v <<

"," << a1.b.k << endl;

cout << a2.v << "," << a2.b.k << endl;}

Big(int n):v(n),b(n){ }Big(Big & x):v(x.v),b(x.b.k){ }

北京大学《程序设计实习》课程

运算符重载 (1)

程序输出结果如下,请填空4,1请写出被隐藏的部分, MyInt 的成员函数里不允许使用静态变量

class MyInt{

int nVal;public: MyInt( int n) { nVal = n ;} int ReturnVal() { return nVal;} ………………….

};

main () { MyInt objInt(10);

objInt-2-1-3;cout <<

objInt.ReturnVal();cout <<",";objInt-2-1;cout <<

objInt.ReturnVal();}MyInt & operator -( int x)

{ nVal -= x; return * this;}

北京大学《程序设计实习》课程

运算符重载 (2)

* 程序输出结果如下,请填空(4,5)(7,8)

class Point {private:

int x;int y;

public: Point(int x_,int y_ ):x(x_),y(y_) { };

_____;}; _____ operator << (_____, const

Point & p){ _____;

return ______;}

main(){ cout << Point(4,5) << Point(7,8);}

北京大学《程序设计实习》课程

运算符重载 (2)

class Point {private:

int x;int y;

public: Point(int x_,int y_ ):x(x_),y(y_) { };

_____;}; _____ operator << (_____, const

Point & p){ _____;

return ______;}

friend ostream & operator << ( ostream & o, const Point & p);

ostream & operator << ( ostream & o, const Point & p)

o << "(" << p.x << "," << p.y << ")" << endl; o

北京大学《程序设计实习》课程

运算符重载 (3)

* 程序输出结果如下,写一个二维数组类 Array20,1,2,3,4,5,6,7,8,9,10,11next0,1,2,3,4,5,6,7,8,9,10,11

北京大学《程序设计实习》课程

运算符重载 (3)

using std::cout;using std::endl;int main(){ Array2 a(3,4); int i,j; for( i = 0;i < 3; i ++ ) for( j = 0; j < 4; j ++ )

a[i][j] = i * 4 + j; for( i = 0;i < 3; i ++ ) { for( j = 0; j < 4; j ++ ) {

cout << a(i,j) << ",";

} cout << endl; }

cout << "next" << endl; Array2 b; b = a; for( i = 0;i < 3; i ++ ) { for( j = 0; j < 4; j ++ ) {

cout << b[i][j] << ",";

} cout << endl; } return 0;}

北京大学《程序设计实习》课程

运算符重载 (3)

class Array2 {private: int * p; int r,c;public: Array2() { p = NULL ; } Array2( int r_, int c_ ):r(r_),c(c_) { p = new int [ r * c]; } Array2( Array2 & a ):r(a.r),c(a.c) { p = new int [r * c]; memcpy( p, a.p, sizeof(int )*r*c); }

Array2 & operator=(const Array2 & a) { if( p ) delete [] p; r = a.r; c = a.c;p = new int [r * c]; memcpy( p, a.p, sizeof(int ) * r * c); return * this;}~Array2() { if( p) delete [] p; }int * operator [] ( int i ) { return p + i * c; }int & operator() ( int i,int j ) { return p[ i * c + j]; }注:重载的实际上是第二维的 [] ,第一维

的 [] 直接调用 int 型一维数组的定义

北京大学《程序设计实习》课程

运算符重载 (3) :第二种解法class CWordArr{private: int *m_pdat; long m_size;public: CWordArr(long size) { m_pdat= new int[size]; m_size = size; }; ~CWordArr() { delete[] m_pdat; }; int& operator[](long idx) { return m_pdat[idx]; }};

北京大学《程序设计实习》课程

运算符重载 (3) :第二种解法class Array2{private: CWordArr **m_p; long m_col,m_row;public: Array2(long col,long row) { m_p=new CWordArr*[col]; for (long i=0;i<col;i++) m_p[i]= new CWordArr(row); m_col=col; m_row=row; }

~ Array2() { for (long i=0;i<m_col;i++) {

delete m_p[i]; m_p[i]=NULL;

} delete[] m_p; } CWordArr& operator[](long idx) { return *m_p[idx]; } int & operator() ( int i,int j ) {

return (*m_p[i])[j];}}

通过两次 [] 重载的叠加,就可以用 a[x][y] 的方式来访问数组元素•C++ 不可能在一个类里面实现 [][] 的重载 ( 若这种相当于三元算符 ) ,因此有两个类:一个是一维数组类,实现 [] 的重载;另一个类是二维数组类,必须持有一组一维数组类的实例,存放二维数组的各个行的数组,二维数组类也要重载 [] 运算符

北京大学《程序设计实习》课程

运算符重载 (4)

程序输出结果如下,写一个 HugeInt 类 1)1000000890000002)1000000890000003)100004)100005)100016)100067)100000089010006

北京大学《程序设计实习》课程

运算符重载 (4)

void main(){ CHugeInt a("1234545436342424354354365289899834234235");

CHugeInt d(9999);CHugeInt temp =

CHugeInt("100000088888888") + 111112;CHugeInt temp2 =

111112+CHugeInt("100000088888888");cout << "1)" << temp << endl;cout << "2)" << temp2 << endl;cout << "3)" << ++d << endl;cout << "4)" << d++ << endl;cout << "5)" << d << endl;d += 5;cout << "6)" << d << endl;cout << "7)" << d + temp;

}

北京大学《程序设计实习》课程

运算符重载 (4)

代码过多,只截取部分

// 重载运算符 +CHugeInt operator +(const CHugeInt & n) const { CHugeInt tmp( * this); for( int i = 0;i < MAX ; i ++ ) {

tmp.Number[i] += n.Number[i]; // 逐位相加

if( tmp.Number[i] >= 10 ) { // 看是否要进位

tmp.Number[i] -= 10;

tmp.Number[i+1] ++;// 进位

} } return tmp;}

const CHugeInt & operator++() { * this = ( * this ) + 1; return * this;}// ++nconst CHugeInt operator++(int n) { CHugeInt tmp = * this; * this = ( * this ) + 1; return tmp;}//n++const CHugeInt operator +=( const CHugeInt & n){ * this = ( * this ) + n; return * this;}

北京大学《程序设计实习》课程

运算符重载 (4)

friend ostream & operator << (ostream & o, const CHugeInt & n);friend CHugeInt operator+ ( int n1 , const CHugeInt & n2);CHugeInt operator + ( int n1 ,const CHugeInt & n2){ return n2 + n1; }ostream & operator << ( ostream & o, const CHugeInt & n){ bool bStart = false; for( int i = MAX -1; i >= 0 ; i -- ) { if( n.Number[i] ) { bStart = true; } if( bStart ) cout << n.Number[i]; } if( !bStart )// 没有数字时,输出 0 cout << 0; return o;}

北京大学《程序设计实习》课程

继承和多态 (1)

程序输出结果如下,写一个 Mystring 类1. abcd-efgh-abcd-2. abcd-3.4. abcd-efgh-5. efgh-6. c7. abcd-8. ijAl-9. ijAl-mnop10. qrst-abcd-11. abcd-qrst-abcd- uvw xyz

aboutbigmetakeabcdqrst-abcd-

北京大学《程序设计实习》课程

Mystring 类 (1)

#include<iostream>#include<cstring>using namespace std;class MyString{public: char *p; MyString() // 构造函数 { p = NULL; } MyString(char *t) // 构造函数 { p = new char[strlen(t) + 1]; strcpy(p,t); } MyString(const MyString &s) // 复制构造函数 { p = new char[strlen(s.p) + 1]; strcpy(p, s.p); }

北京大学《程序设计实习》课程

Mystring 类 (2)

~MyString() // 析构函数{ if(p) delete[]p; }MyString operator+(const MyString &s) // + 号重载,这里表示 // 两个 MyString 类型相加的情况{ char *q; q = new char[strlen(p) + strlen(s.p)+1]; strcpy(q, p); strcat(q, s.p); MyString temp(q); delete []q; return temp; }

北京大学《程序设计实习》课程

Mystring 类 (3)

MyString operator+(const char *s) // + 号重载,这里表示 //MyString 类型 + 字符串的情形 { char *q; q = new char[strlen(p) + strlen(s) + 1]; strcpy(q, p); strcat(q, s); MyString temp(q); delete []q; return temp; } MyString& operator=(const MyString &s) // 赋值号重载 { if(p!=NULL) { delete[]p; } p = new char[strlen(s.p)+1]; strcpy(p, s.p); return *this; }0

北京大学《程序设计实习》课程

Mystring 类 (4)

char &operator[](int n) // [] 号重载 { return p[n]; } MyString& operator+=(char *s) // += 号重载 { char *q; q = new char[strlen(p)+1]; strcpy(q, p); if(p != NULL) { delete []p; } p = new char[strlen(p) + strlen(s) + 1]; strcpy(p,q); strcat(p,s); delete []q; return *this; }

北京大学《程序设计实习》课程

Mystring 类 (5)

MyString operator()(int i, int n) { // () 重载 char *q;

q = new char[n+1]; strncpy(q, p+i, n); q[n] = '\0'; MyString temp(q); delete []q; return temp; }};ostream &operator<< (ostream &o, const MyString &s) // << 号重载{ o << s.p; return o; }MyString operator+(char *s, const MyString &t) // + 号重载,这里是字符串 +MyString 的情形{ char q[100]; strcpy(q, s); strcat(q, t.p); return MyString(q);}

北京大学《程序设计实习》课程

Mystring 类 (6)

// <,==,> 号的重载int operator<(const MyString &s1, const MyString &s2) { if(strcmp(s1.p,s2.p) < 0) { return 1; } else { return 0; }}int operator==(const MyString &s1, const MyString &s2){ if(!strcmp(s1.p, s2.p)) { return 1; } else { return 0; }}int operator>(const MyString &s1, const MyString &s2){ if(strcmp(s1.p, s2.p) > 0) { return 1; } else { return 0; }}

北京大学《程序设计实习》课程

Mystring 类 (8)

从 string 类派生的写法

class MyString : public string{public:MyString():string() {};MyString( const char * s):string(s){};MyString( const string & s ): string(s)

{};MyString operator() ( int s, int l){ return this->substr(s,l);};

};

北京大学《程序设计实习》课程

继承和多态 (2)

写出下面程序的运行结果class B {private: int nBVal;public: void Print() { cout << "nBVal="<< nBVal

<< endl; } void Fun() {cout << "B::Fun" << endl; } B ( int n ) { nBVal = n;}};

class D:public B {private : int nDVal;public: void Print() { B::Print(); cout <<

"nDVal="<<nDVal <<endl;

} D( int n) : B(3*n) {nDVal

= n;} void Fun() { cout << "D::Fun" <<

endl; }};

北京大学《程序设计实习》课程

继承和多态 (2)

main() { B * pb; D * pd; D d(4); d.Fun(); pb = new B(2);

pd = new D(8); pb -> Fun(); pd->Fun(); pb->Print (); pd->Print

(); pb = & d; pb->Fun(); pb->Print();}

D::FunB::FunD::FunnBVal=2nBVal=24nDVal=8B::FunnBVal=12

北京大学《程序设计实习》课程

继承和多态 (3)

程序输出结果如下,请填空A::FunA::DoA::FunC::Do

class A {private: int nVal;public: void Fun() { cout << "A::Fun" << endl; }; virtual void Do() { cout << "A::Do" << endl; }};

class B:public A {public: virtual void Do() { cout << "B::Do" << endl;}};class C:public B {public: void Do( ) { cout <<"C::Do"<<endl; }

void Fun() { cout << "C::Fun" << endl; }};

北京大学《程序设计实习》课程

继承和多态 (3)

void Call(____________)

{ p->Fun(); p-

>Do();}main() { Call( new A()); Call( new C());}

A * p void Call(____________)

{ p.Fun(); p.Do();}main() { Call(A()); Call(C());}

A & p

北京大学《程序设计实习》课程

模板 (1)

* 设计 CLinkList 类模板中 AppendNode 和 PrintList 成员函数,得到如下结果

0,1,2,3,0,1,2,3,9,10,11,注意:1) 不得调用任何库函数,库模板,不得使用 static 关键字,不得使

用除 NULL 以外的任何常量2) 不得为 Node 和 CLinkList 模板添加任何成员3) 不得添加任何全局变量,不得添加其他函数

北京大学《程序设计实习》课程

模板 (1)

template <class D>class Node {public: D data; Node * next;};template<class D>class CLinkList {private: Node<D> * pHead;public: CLinkList(); void AppendNode( D data); void PrintList();};

template<class D>CLinkList<D>::CLinkList()

{ pHead = new

Node<D>; pHead->next = NULL;};main(){ CLinkList<int> l; for( int i = 0;i < 4;i ++) l.AppendNode(i); l.PrintList(); cout << endl; for( i = 9;i < 12;i ++) l.AppendNode(i); l.PrintList();}

北京大学《程序设计实习》课程

模板 (1)

template<class D>void CLinkList<D>::AppendNode( D data){

Node<D> * p = pHead;

while( p->next )p = p->next;

p->next = new Node<D>;

p = p->next;p->data = data;p->next = NULL;

}

template<class D>void CLinkList<D>::PrintList(){ Node<D> * p = pHead; while( p->next ) { cout << p->next-

>data << ","; p = p->next; }}

北京大学《程序设计实习》课程

模板 (2)

填空使程序能编译通过 , 并写出运行的输出结果 #include <iostream>

template <_____________>class myclass { T i;public: myclass (T a) { i = a; } void show( ) { cout << i << endl;

}};void main() { myclass<________> obj("This"); obj.show();}

class T

char *

该程序输出结果为: _____This

北京大学《程序设计实习》课程

模板 (2)

填空得到以下结果TomHanks

注意,不允许使用任何常量 template <class T> class myclass {

_________;int nSize;

public:myclass ( ______________, int n)

{p = new T[n];for( int i = 0;i < n;i ++ )

p[i] = a[i];nSize = n;

}

~myclass( ) { delete [] p; } void Show() { for( int i = 0;i < nSize;i ++ ) {

cout << p[i];}

}};main() { char * szName = "TomHanks"; myclass<char > obj (___________________ _); obj.Show();}

T * p

T * a

szName,strlen(szName)

北京大学《程序设计实习》课程

STL(1)

看程序写结果class A {private : int nId;public: A(int n) { nId = n; cout << nId << " contructor" << endl; }; A( const A & a ) { nId = a.nId ; cout << nId << " copy constructor"

<< endl; } ~A( ) { cout << nId << " destructor" << endl; }};

main(){ vector<A*> vp; vp.push_back(new A(1)); vp.push_back(new A(2)); vector<A> v; v.push_back (3);}

1 contructor2 contructor3 contructor3 copy constructor3 destructor3 destructor

北京大学《程序设计实习》课程

STL(2)

程序输出结果如下,请填空Tom,Jack,Mary,John ,

template <_______ , _______>class MyClass { T array[T2]; public: MyClass( T * begin ) { copy( begin, begin + T2, array); } void List() { T * i;

for( i = array; i != array + T2;i ++)

cout << * i << "," ; }};

main(){ string array[4] = { "Tom","Jack","Mary","John"}; _____________________ ; obj.List();}

class T int T2

MyClass<string,4> obj(array)

北京大学《程序设计实习》课程

STL(3)

程序输出结果如下,请填空Tom,Jack,Mary,John,

template <class T>class MyClass { vector<T> array;public: MyClass ( T * begin,int n ):array(n) { copy( begin, begin + n, array.begin()); } void List() { ________________________; for( i = array.begin(); i != array.end();i ++) cout << * i << "," ; }};

main(){ string array[4] = { "Tom","Jack","Mary","John"

};_________________________; obj.List();}

vector<T>::iterator i;

MyClass<string> obj( array,4)

北京大学《程序设计实习》课程

STL(4)

程序输出结果如下,请填空1 2 6 7 8 9main(){

int a[] = {8,7,8,9,6,2,1};___________________;for( int i = 0;i < 7;i ++ )

___________________;ostream_iterator<int> o(cout," ");copy( v.begin(),v.end(),o);

}

set<int >v

v.insert(a[i])

北京大学《程序设计实习》课程

STL(5)

程序输出结果如下,请填空A::Print: 1B::Print: 2B::Print: 3

template <class T>void PrintAll( const T & c ){ T::const_iterator i; for( i = c.begin(); i != c.end(); i ++ ) _______________________;};class A {protected: int nVal;public: A(int i):nVal(i) { } virtual void Print() { cout << "A::Print: " << nVal << endl; }};

(*i)->Print()

北京大学《程序设计实习》课程

STL(5)class B:public A {public: B(int i):A(i) { } void Print() { cout << "B::Print: " << nVal << endl; }};main(){ __________________; v.push_back( new A(1)); v.push_back (new B(2)); v.push_back (new B(3)); PrintAll( v);}

vector<A*> v

北京大学《程序设计实习》课程

STL(6)

* 写一个自己的 CMyostream_iterator 模板,使之能和 ostream_iterator 模板达到一样的效果

using namespace std;main(){ int a[5] = {1,2,3,4,5}; CMyostream_iterator<int> output(cout,"*"); vector<int> v(a,a+5); copy(v.begin(),v.end(),output);}

北京大学《程序设计实习》课程

提示 参考 copy 的 helptemplate<class InIt, class OutIt> OutIt copy(InIt first, InIt last, OutIt x); The template function evaluates *(x + N) = *(first + N))

once for each N in the range [0, last - first), for strictly increasing values of N beginning with the lowest value. It then returns x + N. If x and first designate regions of storage, x must not be in the range [first, last)

copy 的源代码:template<class _II, class _OI> inline

_OI copy(_II _F, _II _L, _OI _X){for (; _F != _L; ++_X, ++_F)

*_X = *_F;return (_X); }

47

要支持 copy 函数必须重载三个运算符: *,=,++

北京大学《程序设计实习》课程

STL(6)

template <class T>class CMyostream_iterator{private: ostream & o; string s;public: CMyostream_iterator( ostream & output,

const char * sz): o(output),s(sz) {} void operator++() { }; void operator=(const T & val ) { o << val << s; } CMyostream_iterator & operator * ( ) { return * this; }};

北京大学《程序设计实习》课程

STL(7)

程序输出结果如下,请填空5*3*4*2*1*1*2*3*4*5*1*2*9*4*5*

template <class T>class MyClass: public list<T>{ public: ____________________ (int n) { iterator i; int k = 0; for( ____________________________) { if( k == n) return _______________;

k ++; } } MyClass(int n):___________________ {}};

main(){ MyClass<int> obj(5); int a[] = { 5, 3, 4, 2,1 }; copy( a, a + 5, obj.begin()); ostream_iterator<int> output (cout,"*"); copy( obj.begin(),obj.end(),output); cout << endl; obj.sort(); copy( obj.begin(),obj.end(),output); cout << endl; obj[2] = 9; copy( obj.begin(),obj.end(),output);}

T& operator[]

i=begin();i != end(); i ++* i

list<T>(n)

注意: list 容器类派生类的初始化

北京大学《程序设计实习》课程

STL(8)

标准矩形问题 其边平行于坐标轴 给定不重复的 n 个整点 ( 横、纵坐标都是整数的点 ) ,求

从这 n 个点中任取 4 点作为顶点所构成的四边形中,有多少个是标准矩形。

输入数据:第一行是点的数目其后每一行都代表一个点,由两个整数表示,第一个是 x 坐标,第二个是 y 坐标输出要求 :输出标准矩形的数目

北京大学《程序设计实习》课程

STL(8)

struct Point { int x; int y; Point( int x_,int y_):x(x_),y(y_) { }};bool operator < ( const Point & p1, const Point & p2){ if( p1.y < p2.y ) return true; else if( p1.y == p2.y ) return p1.x < p2.x; else return false;}

main(){ int t; int x,y; cin >> t; vector<Point> v; while( t -- ) { cin >> x >> y; v.push_back(Point(x,y)); } _____________________; vector<Point>::iterator i,j;

int nTotalNum = 0;

sort(v.begin(),v.end())

北京大学《程序设计实习》课程

STL(8) for( i = v.begin(); i < v.end() - 1;i ++ ) for(___________; ___________; _________) { if(binary_search( v.begin(),v.end(), Point( j->x, i->y)) && ___________________________________________ &&____________________________________________ && ______________________________________________ ) nTotalNum ++; } cout << _________________;};

j = i + 1 j < v.end() j ++

binary_search( v.begin(),v.end(),Point( i->x, j->y))

i->x != j->x

i->y != j->y

nTotalNum / 2

北京大学《程序设计实习》课程

STL(9)

程序员马克斯的程序风格和他的性格一样怪异。很不幸他被开除后老板命令你接替他的工作。马克斯走之前愤然删除了他写的一个类模板 MyMax 中的一些代码,你只好将其补出来。你只知道 MyMax 模板的作用与求数组或向量中的最大元素有关,而且下面程序的输出结果是:

  5136

请补出马克斯删掉的那部分代码。该部分代码全部位于 “ // 开头” 和 “ // 结尾”之间,别处一个字节也没有。

北京大学《程序设计实习》课程

STL(9)

*MyMax 模板 不准使用除 true 和 false 以外的任何常量 , 并且不得假设 true 的值是

1 或任何值 不得使用任何库函数或库模板 ( 包括容器和算法 ) 不得使用 static 关键字 。 提示: copy 函数模板的第三个参数是传值的

template <class T>class MyMax{ public: T * pMax; // 指向用于存放最大值的变量 bool bFirst; // 记录最大值时会用到的标记 MyMax (T * p):bFirst(true),pMax(p) { };// 开头//……// 结尾};

MyMax模板的作用与求数组或向量中的最大元素有关,而且下面程序的输出结果是:5136请补出马克斯删掉的那部分代码。

北京大学《程序设计实习》课程

STL(9)class A {public: int i; A( int n) :i(n) { }; A() { };};bool operator < ( const A & a1, const A & a2){ return a1.i < a2.i ; }ostream & operator<< ( ostream & o, const A & a){ o << a.i; return o; }

main(){ A a[5] =

{A(1),A(5),A(3),A(4),A(2)}; int b[9] =

{1,5,30,40,2,136,80,20,6}; int nMax; A aMax; MyMax<A> outputa( & aMax); copy(a,a+5,outputa); cout << outputa() << endl; MyMax<int> output( & nMax); copy(b,b+9,output); cout << output() << endl;}

北京大学《程序设计实习》课程

STL(9)

//需要实现支持 copy 函数的三个运算符重载,以及 () 算符

MyMax & operator * () { return * this; }void operator ++( ) {}void operator = ( T & obj) { if( bFirst) { * pMax = obj; bFirst = false; } else { if( * pMax < obj ) * pMax = obj; } }T operator() () { return * pMax; }

北京大学《程序设计实习》课程

课后参考 2004 年考题及答案 2006 年考题及答案