数据结构C++笔记

基础要打牢,重学一下数据结构。

第一章

递归函数

对于函数f (n) 的一个递归定义(假定是直接递归) ,要想使它成为一个完整的定义,必须
满足如下条件:
• 定义中必须包含一个基本部分(b a s e) ,其中对于n 的一个或多个值,f  (n)必须是直接定
义的(即非递归) 。为简单起见,我们假定基本部分包含了n≤k 的情况,其中k 为常数。 (在基
本部分中指定n≥k 的情形也是可能的,但较少见。 )
• 在递归部分(recursive component)中,右侧所出现的所有f 的参数都必须有一个比n 小,
以便重复运用递归部分来改变右侧出现的f ,直至出现f 的基本部分。

 

数组

程序1-12   为一个二维数组分配存储空间
template <class T>
bool Make2DArray ( T ** &x, int rows, int cols)
{// 创建一个二维数组
try {
/ /创建行指针
x = new T * [rows];
/ /为每一行分配空间

for (int  i = 0 ; i < rows; i++)
  x[i] = new int [cols];
return true;
}
catch (xalloc) {return false;}
}

或在上面的代码不处理异常,而在调用函数时进行:

try { Make2DArray (x, r, c);}
catch (xalloc) {cerr<< "Could bot create x" << endl;
exit(1) ; }

在Make2DArray中不捕获异常不仅简化了函数的代码设计,而且可以使用户在一个更合适
的地方捕获异常,以便更好地报告出错误的明确含义或进行错误恢复。

程序1-14   释放由Make2DArray所分配的空间
template <class T>
void  Delete2DArray( T ** &x, int rows)
{// 删除二维数组x
/ /释放为每一行所分配的空间
for (int i = 0 ; i < rows ; i++)
delete [ ] x[i];
/ /删除行指针
delete [] x;
x = 0;
}

 

类Currency

注意:在程序1-24 中定义的Currency类中重载了流插入操作符,但没有定义相应的成员函数,而重载 +和+ =时则把它们定义为类成员。同样,也可以重载流抽取操作符>>而不需要把它定义为类成员。

程序1-24   使用操作符重载的类定义
class Currency {
p u b l i c :
// 构造函数
Currency(sign s = plus, unsigned long d = 0, unsigned int c = 0);
// 析构函数
~Currency() {}
bool Set(sign s, unsigned long d, unsigned int c);
bool Set(float a);
sign Sign() const
{if (amount < 0) return minus;
else return plus;}
unsigned long Dollars() const
{if (amount < 0) return (-amount) / 100;
else return amount / 100;}
unsigned int Cents() const
{if (amount < 0)
return -amount - Dollars() * 100;
else return amount - Dollars() * 100;}
Currency operator+(const Currency& x) const;
Currency& operator+=(const Currency& x)
{amount += x.amount; return *this;}
void Output(ostream& out) const;
private:
long amount;
} ;

程序1-25   +,Output和<<的代码
Currency Currency::operator+(const Currency& x) const
{// 把 x 累加至* t h i s .
Currency y;
y.amount = amount + x.amount;
return y;
}
void Currency::Output(ostream& out) const
{// 将currency 的值插入到输出流
long a = amount;
if (a < 0) {out << '-' ; a = -a ; }
long d = a / 100; // 美元
out << '$' << d << '.' ;
int c = a - d * 100; // 美分
if (c < 10) out << "0";
out << c;
}
// 重载< <
ostream& operator<<(ostream& out, const Currency& x)

{x.Output(out); return out;}

如果在程序1-24中类的定义中加上:

class Currency {
friend ostream& operator<< (ostream&, const Currency&);
public:

......

}

则可以在<<的重载中访问private成员变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值