当前位置:   article > 正文

C++经典程序代码大全_c++代码

c++代码
  1. //根据半径计算圆的周长和面积
  2. #include <iostream.h>
  3. const float PI=3.1416; //声明常量(只读变量)PI为3.1416
  4. float fCir_L(float); //声明自定义函数fCir_L()的原型
  5. float fCir_S(float); //声明自定义函数fCir_S()的原型
  6. //以下是main()函数
  7. main()
  8. {
  9. float r,l,s; //声明3个变量
  10. cout<<"r="; //显示字符串
  11. cin>>r; //键盘输入
  12. l=fCir_L(r); //计算圆的周长,赋值给变量l
  13. s=fCir_S(r); //计算圆的面积,赋值给变量s
  14. cout<<"l="<<l; //显示计算结果
  15. cout<<"\ns="<<s;
  16. }
  17. //定义计算圆的周长的函数fCir_L()
  18. float fCir_L(float x)
  19. {
  20. float z=-1.0; //声明局部变量
  21. if (x>=0.0) //如果参数大于0,则计算圆的周长
  22. z=2*PI*x;
  23. return(z); //返回函数值
  24. }
  25. //定义计算圆的面积的函数fCir_S()
  26. float fCir_S(float x)
  27. {
  28. float z=-1.0; //声明局部变量
  29. if (x>=0.0) //如果参数大于0,则计算圆的面积
  30. z=PI*x*x;
  31. return(z); //返回函数值
  32. }
  33. /* Program: P1-2.CPP
  34. Written by: Hap
  35. Date written: 02:11:10
  36. */
  37. #include <iostream.h>
  38. void main(void)
  39. {
  40. double s1,s2,s3;
  41. s1=1.5; /* 对变量s1赋值*/
  42. cout<<"s1="<<s1<<endl;
  43. /* 对变量s2赋值*/ s2=2.5;
  44. cout<<"s2="<<s2<<endl;
  45. s3= /* 对变量s3赋值*/ 3.5;
  46. cout<<"s3="<<s3<<endl;
  47. cout<<"s1+s2+s3="<<s1+s2+s3<<endl; //计算并显示
  48. //计算并显示 cout<<"s1+s2+s3="<<s1+s2+s3<<endl;
  49. }
  50. #include <iostream.h>
  51. main()
  52. {
  53. double r=1.0;
  54. cout<<"r="<<r<<endl;
  55. double l;
  56. l=2*3.1416*r; //计算圆的周长,赋值给变量l
  57. cout<<"l="<<l<<endl; //显示圆的周长
  58. double s=3.1416*r*r; //计算圆的面积,赋值给变量s
  59. cout<<"s="<<s<<endl; //显示圆的面积
  60. cout<<"r="; //显示提示输入的信息
  61. cin>>r; //键盘输入
  62. l=2*3.1416*r; //计算圆的周长,赋值给变量l
  63. cout<<"l="<<l<<endl; //显示圆的周长
  64. s=3.1416*r*r;
  65. cout<<"s="<<s<<endl; //显示圆的面积
  66. }
  67. #include <iostream.h> //包含iostream.h头文件
  68. void main()
  69. {
  70. //输出字符常量、变量和字符串
  71. char c1='A';
  72. cout<<'W';
  73. cout<<c1<<endl;
  74. cout<<"This is a test."<<endl;
  75. cout<<"------------------"<<endl;
  76. //输出整型常量、变量和表达式
  77. int n=100;
  78. cout<<10;
  79. cout<<n;
  80. cout<<2*n<<endl; //输出整型表达式
  81. cout<<"------------------"<<endl;
  82. //输出浮点型常量、变量和表达式
  83. double pi=3.1415926,r=10.0,s=pi*r*r;
  84. cout<<pi<<endl;
  85. cout<<r;
  86. cout<<s;
  87. cout<<2*r*pi<<endl; //输出浮点型表达式
  88. cout<<"------------------"<<endl;
  89. //一个cout可以输出多项数据
  90. cout<<'W'<<" "<<c1<<endl;
  91. cout<<"This is a test."<<endl;
  92. cout<<"pi="<<pi<<" r="<<r<<" s="<<s<<endl;
  93. }
  94. #include <iostream.h> //包含iostream.h头文件
  95. main()
  96. {
  97. //输入输出字符
  98. char c;
  99. cin>>c;
  100. cout<<"c="<<c<<endl;
  101. //输入输出整型数据
  102. int n;
  103. cin>>n;
  104. cout<<"n="<<n<<endl;
  105. //输入输出浮点型数据
  106. double x;
  107. cin>>x;
  108. cout<<"x="<<x<<endl;
  109. //输入提示
  110. cout<<"n=";
  111. cin>>n;
  112. cout<<"n="<<n<<endl;
  113. //多项输入
  114. cout<<"c n x"<<endl;
  115. cin>>c>>n>>x;
  116. cout<<"c="<<c<<" n="<<n<<" x="<<x<<endl;
  117. }
  118. #include <iostream.h> //包含iostream.h头文件
  119. main()
  120. {
  121. //声明整型变量
  122. int a,b;
  123. //从键盘上为整型变量赋值
  124. cout<<"a=";
  125. cin>>a;
  126. cout<<"b=";
  127. cin>>b;
  128. //整型数的算术运算
  129. cout<<a<<"+"<<b<<"="<<a+b<<endl;
  130. cout<<a<<"-"<<b<<"="<<a-b<<endl;
  131. cout<<a<<"*"<<b<<"="<<a*b<<endl;
  132. cout<<a<<"/"<<b<<"="<<a/b<<endl;
  133. cout<<a<<"%"<<b<<"="<<a%b<<endl;
  134. //测试溢出
  135. short n=32767,m; //n取short类型的最大值
  136. cout<<"n="<<n<<endl;
  137. m=n+1; //引起溢出
  138. cout<<"n+1="<<m<<endl;
  139. }
  140. #include <iostream.h> //包含iostream.h头文件
  141. main()
  142. {
  143. //声明变量,并初始化
  144. int a=010,b=10,c=0X10;
  145. //以十进制形式显示数据
  146. cout<<"DEC:";
  147. cout<<" a="<<a;
  148. cout<<" b="<<b;
  149. cout<<" c="<<c<<endl;
  150. //以八进制形式显示数据
  151. cout<<"OCT:";
  152. cout<<oct; //指定八进制输出
  153. cout<<" a="<<a;
  154. cout<<" b="<<b;
  155. cout<<" c="<<c<<endl;
  156. //以十六进制形式显示数据
  157. cout<<"HEX:";
  158. cout<<hex; //指定十六进制输出
  159. cout<<" a="<<a;
  160. cout<<" b="<<b;
  161. cout<<" c="<<c<<endl;
  162. //八、十和十六进制数混合运算并输出
  163. cout<<"a+b+c=";
  164. cout<<dec; //恢复十进制输出
  165. cout<<a+b+c<<endl;
  166. //测试八、十和十六进制输入
  167. cout<<"DEC:a="; cin>>a;
  168. cout<<"OCT:b="; cin>>b;
  169. cout<<"HEX:a="; cin>>c;
  170. cout<<"DEC:"<<dec<<endl; //指定十进制输出
  171. cout<<"a="<<a<<endl;
  172. cout<<"b="<<b<<endl;
  173. cout<<"c="<<c<<endl;
  174. }
  175. #include <iostream.h> //包含iostream.h头文件
  176. #include<iomanip.h> // iomanip.h头文件包含setprecision()的定义
  177. main()
  178. {
  179. //float型变量的声明、输入、计算和输出
  180. float fx,fy;
  181. cout<<"fx=";
  182. cin>>fx;
  183. cout<<"fy=";
  184. cin>>fy;
  185. cout<<fx<<"+"<<fy<<"="<<fx+fy<<endl;
  186. cout<<fx<<"-"<<fy<<"="<<fx-fy<<endl;
  187. cout<<fx<<"*"<<fy<<"="<<fx*fy<<endl;
  188. cout<<fx<<"/"<<fy<<"="<<fx/fy<<endl<<endl;
  189. //cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!
  190. //double型变量的声明、输入、计算和输出
  191. float dx,dy;
  192. cout<<"dx=";
  193. cin>>dx;
  194. cout<<"dy=";
  195. cin>>dy;
  196. cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl;
  197. cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl;
  198. cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;
  199. cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<<endl;
  200. //cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!
  201. //测试float和double类型数据的有效位
  202. fx=10.0;fy=6.0;
  203. float fz=fx/fy;
  204. dx=10.0;dy=6.0;
  205. double dz=dx/dy;
  206. cout<<"fz=";
  207. cout<<setprecision(20)<<fx<<"/"<<fy<<"="<<fz<<endl;
  208. cout<<"dz=";
  209. cout<<setprecision(20)<<dx<<"/"<<dy<<"="<<dz<<endl<<endl;;
  210. //float型溢出
  211. float x=3.5e14;
  212. cout<<"x="<<x<<endl;
  213. cout<<"x*x="<<x*x<<endl;
  214. cout<<"x*x*x="<<x*x*x<<endl;
  215. }
  216. #include <iostream.h> //包含iostream.h头文件
  217. main()
  218. {
  219. //字符类型变量的声明
  220. char c1='A';
  221. char c2;
  222. //字符数据的运算及输出
  223. c2=c1+32;
  224. cout<<"c1="<<c1<<endl;
  225. cout<<"c2="<<c2<<endl;
  226. //输出字符及ASCII码
  227. cout<<c1<<" : "<<int(c1)<<endl;
  228. cout<<c2<<" : "<<int(c2)<<endl;
  229. cout<<'$'<<" : "<<int('$')<<endl;
  230. //输入字符
  231. cout<<"c1 c2"<<endl;
  232. cin>>c1>>c2;
  233. cout<<"c1="<<c1<<" c2="<<c2<<endl;
  234. }
  235. #include <iostream.h> //包含iostream.h头文件
  236. main()
  237. {
  238. char c1='\a',TAB='\t';
  239. //阵铃一声
  240. cout<<c1<<endl;
  241. //使用水平制表符
  242. cout<<1<<TAB<<2<<TAB<<3<<TAB<<4<<endl;
  243. //使用双引号
  244. cout<<"He said \"Thank you\"."<<endl;
  245. //使用回车换行
  246. cout<<"abc\n"<<"def"<<'\n';
  247. }
  248. #include <iostream.h> //包含iostream.h头文件
  249. main()
  250. {
  251. //声明bool变量,并初始化
  252. bool flag1=false,flag2=true;
  253. //输出布尔常量和变量
  254. cout<<"false:"<<false<<endl;
  255. cout<<"true: "<<true<<endl;
  256. cout<<"flag1="<<flag1<<endl;
  257. cout<<"flag2="<<flag2<<endl;
  258. //布尔变量的赋值和输出
  259. int x=1;
  260. flag1=x>0; //存放关系运算结果
  261. cout<<"flag1="<<flag1<<endl;
  262. flag2=flag1; //bool类型变量相互赋值
  263. cout<<"flag2="<<flag2<<endl;
  264. //布尔变量超界处理
  265. flag1=100;
  266. cout<<"flag1="<<flag1<<endl;
  267. flag2=-100;
  268. cout<<"flag2="<<flag2<<endl;
  269. }
  270. #include <iostream.h>
  271. const double PI=3.1416; //声明常量(const变量)PI为3.1416
  272. main()
  273. {
  274. //声明3个变量
  275. double r,l,s;
  276. //输入圆的半径
  277. cout<<"r=";
  278. cin>>r;
  279. //计算圆的周长
  280. l=2*PI*r;
  281. cout<<"l="<<l<<endl;
  282. //计算圆的面积
  283. s=PI*r*r;
  284. cout<<"s="<<s<<endl;
  285. }
  286. #include<iostream.h>
  287. main()
  288. {
  289. //定义枚举类型,并指定其枚举元素的值
  290. enum color {
  291. RED=3,
  292. YELLOW=6,
  293. BLUE=9
  294. };
  295. //声明枚举变量a和b,并为枚举变量a赋初值
  296. enum color a=RED;
  297. color b; //合法,与C语言不同
  298. // 输出枚举常量
  299. cout<<"RED="<<RED<<endl;
  300. cout<<"YELLOW="<<YELLOW<<endl;
  301. cout<<"BLUE="<<BLUE<<endl;
  302. //枚举变量的赋值和输出
  303. b=a;
  304. a=BLUE;
  305. cout<<"a="<<a<<endl;
  306. cout<<"b="<<b<<endl;
  307. //a=100; 错误!
  308. //a=6 也错误!
  309. //枚举变量的关系运算
  310. b=BLUE; // 枚举变量的赋值运算
  311. cout<<"a<b="<<(a<b)<<endl;
  312. }
  313. #include <iostream.h>
  314. const double PI=3.1416; //声明常量(const变量)PI为3.1416
  315. main()
  316. {
  317. //声明3个变量
  318. double r=3,l,s;
  319. //计算圆的周长
  320. l=2*PI*r;
  321. cout<<"l="<<l<<endl;
  322. //计算圆的面积
  323. s=PI*r*r;
  324. cout<<"s="<<s<<endl;
  325. //验证赋值误差
  326. int il,is;
  327. il=l;
  328. is=s;
  329. cout<<"il="<<il<<endl;
  330. cout<<"is="<<is<<endl;
  331. }
  332. #include <iostream.h>
  333. main()
  334. {
  335. //变量声明
  336. char c;
  337. double x,y;
  338. //测试自增
  339. cout<<"++E and E++ :"<<endl;
  340. c='B';
  341. cout<<"c="<<++c<<endl; //输出c=C
  342. c='B';
  343. cout<<"c="<<c++<<endl; //输出c=B
  344. x=1.5;
  345. y=5+ ++x; //加号后的空格不能少
  346. cout<<"y="<<y<<endl; //输出y=7.5
  347. x=1.5;
  348. y=5+x++;
  349. cout<<"y="<<y<<endl; //输出y=6.5
  350. cout<<"--------------------"<<endl;
  351. //测试自减
  352. cout<<"--E and E-- :"<<endl;
  353. c='B';
  354. cout<<"c="<<--c<<endl; //输出c=A
  355. c='B';
  356. cout<<"c="<<c--<<endl; //输出c=B
  357. x=1.5;
  358. y=5+--x;
  359. cout<<"y="<<y<<endl; //输出y=5.5
  360. x=1.5;
  361. y=5+x--;
  362. cout<<"y="<<y<<endl; //输出y=6.5
  363. }
  364. #include <iostream.h>
  365. main()
  366. {
  367. int a=3, b=2;
  368. //输出关系表达式
  369. cout<<a<b<<endl;
  370. cout<<(a<b)<<(a>b)<<(a>=b)<<(a==b)<<(a!=b)<<endl;
  371. bool flag=2*a<b+10;
  372. cout<<"flag="<<flag;
  373. }
  374. #include <iostream.h>
  375. main()
  376. {
  377. float a=3.5,b=2.1,c=0;
  378. cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;
  379. //与运算
  380. cout<<"a&&b="<<(a&&b)<<endl;//输出1
  381. cout<<"a&&c="<<(a&&c)<<endl;//输出0
  382. //或运算
  383. cout<<"a||b="<<(a||b)<<endl;//输出1
  384. cout<<"a||c="<<(a||c)<<endl;//输出1
  385. //非运算
  386. cout<<"!a="<<!a<<endl<<"!c="<<!c<<endl;//输出0 1
  387. //关系运算和逻辑运算
  388. bool flag=a>=0 && a<=5; //变量a在[0,5]区间内
  389. cout<<"a=>0 && a<=5="<<flag<<endl;//输出1
  390. //算术运算、关系运算和逻辑运算
  391. cout<<"a+5>2*b+2||a<b+3="<<(a+5>2*b+2||a<b+3)<<endl;//输出1
  392. }
  393. #include <iostream.h>
  394. main()
  395. {
  396. //按位与运算
  397. cout<<"24&12="<<(24&12)<<endl;
  398. //按位异或运算
  399. cout<<"24^12="<<(24^12)<<endl;
  400. //按位或运算
  401. cout<<"24|12="<<(24|12)<<endl;
  402. //按位取反运算
  403. cout<<"~24="<<(~24)<<endl;
  404. //左移位运算
  405. cout<<"5<<3="<<(5<<3)<<endl;
  406. cout<<"-5<<3="<<(-5<<3)<<endl;
  407. //右移位运算
  408. cout<<"5>>3="<<(5>>3)<<endl;
  409. cout<<"-5>>3="<<(-5>>3)<<endl;
  410. }
  411. #include <iostream.h>
  412. main()
  413. {
  414. int a=1,b=1,c=3;
  415. //显示a,b,c的值
  416. cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;
  417. //计算显示(1) b+=a+2*c%5; 的结果
  418. b+=a+2*c%5; //相当于表达式语句 b=b+(a+2*c%5);
  419. cout<<"(1) b="<<b<<endl;
  420. //计算显示(2) a<<=c-2*b; 的结果
  421. a=1,b=1,c=3;
  422. a<<=c-2*b; // 相当于表达式语句 a=a<<(c-2*b);
  423. cout<<"(2) a="<<a<<endl;
  424. //计算显示(3) a*=b=c=3;的结果
  425. a=1,b=1,c=3;
  426. a*=b=c=3; //相当于语句组 c=3;b=c;a=a*b;
  427. cout<<"(3) a="<<a<<" b="<<b<<" c="<<c<<endl;
  428. //计算显示(4) a+=b+=c;的结果
  429. a=1,b=1,c=3;
  430. a+=b+=c; //相当于语句组 b=b+c; a=a+b;
  431. cout<<"(4) a="<<a<<" b="<<b<<" c="<<c<<endl;
  432. //计算显示(5) a-=b=++c+2;的结果
  433. a=1,b=1,c=3;
  434. a-=b=++c+2; //相当于语句组 ++c;b=b+c+2;a=a-b;
  435. cout<<"(5) a="<<a<<" b="<<b<<" c="<<c<<endl;
  436. }
  437. #include <iostream.h>
  438. main()
  439. {
  440. //用 sizeof 计算各类种常量的字节长度
  441. cout<<"sizeof('$')="<<sizeof('$')<<endl;
  442. cout<<"sizeof(1)="<<sizeof(1)<<endl;
  443. cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl;
  444. cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl;
  445. //用sizeof 计算各类型变量的字节长度
  446. int i=100;
  447. char c='A';
  448. float x=3.1416;
  449. double p=0.1;
  450. cout<<"sizeof(i)="<<sizeof(i)<<endl;
  451. cout<<"sizeof(c)="<<sizeof(c)<<endl;
  452. cout<<"sizeof(x)="<<sizeof(x)<<endl;
  453. cout<<"sizeof(p)="<<sizeof(p)<<endl;
  454. //用sizeof 计算表达式的字节长度
  455. cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl;
  456. //用 sizeof 计算各类型的字节长度
  457. cout<<"sizeof(char)="<<sizeof(char)<<endl;
  458. cout<<"sizeof(int)="<<sizeof(int)<<endl;
  459. cout<<"sizeof(float)="<<sizeof(float)<<endl;
  460. cout<<"sizeof(double)="<<sizeof(double)<<endl;
  461. //用sizeof 计算数组的字节长度
  462. char str[]="This is a test.";
  463. int a[10];
  464. double xy[10];
  465. cout<<"sizeof(str)="<<sizeof(str)<<endl;
  466. cout<<"sizeof(a)="<<sizeof(a)<<endl;
  467. cout<<"sizeof(xy)="<<sizeof(xy)<<endl;
  468. //用sizeof 计算自定义类型的长度
  469. struct st {
  470. short num;
  471. float math_grade;
  472. float Chinese_grade;
  473. float sum_grade;
  474. };
  475. st student1;
  476. cout<<"sizeof(st)="<<sizeof(st)<<endl;
  477. cout<<"sizeof(student1)="<<sizeof(student1)<<endl;
  478. }
  479. #include <iostream.h>
  480. main()
  481. {
  482. //声明变量语句中使用顺序运算
  483. int x, y;
  484. //计算中使用顺序运算
  485. x=50;
  486. y=(x=x-5, x/5);
  487. cout<<"x="<<x<<endl;
  488. cout<<"y="<<y<<endl;
  489. }
  490. #include <iostream.h>
  491. main()
  492. {
  493. //测试表达式类型的转换
  494. int n=100,m;
  495. double x=3.791,y;
  496. cout<<"n*x="<<n*x<<endl;
  497. //赋值类型转换
  498. m=x;
  499. y=n;
  500. cout<<"m="<<m<<endl;
  501. cout<<"y="<<y<<endl;
  502. //强制类型转换
  503. cout<<"int(x)="<<int(x)<<endl;
  504. cout<<"(int)x="<<(int)x<<endl;
  505. cout<<"int(1.732+x)="<<int(1.732+x)<<endl;
  506. cout<<"(int)1.732+x="<<(int)1.723+x<<endl;
  507. cout<<"double(100)="<<double(100)<<endl;
  508. }
  509. #include <iostream.h>
  510. main()
  511. {
  512. float a,b,s;
  513. cout<<"a b"<<endl;
  514. cin>>a>>b; //利用cin从键盘上为变量 a,b 赋值
  515. s=a;
  516. if (a<b) {
  517. s=b; //if语句中只有这一个语句,可省略花括号
  518. }
  519. s=s*s; //变量s中保存a,b中较大的一个数的平方
  520. cout<<"s="<<s;
  521. }
  522. #include <iostream.h>
  523. main()
  524. {
  525. int x,y;
  526. cout<<"x=";
  527. cin>>x;
  528. if (x<=0) { //满足条件执行
  529. y=2*x;
  530. cout<<"y="<<y; //输出结果
  531. }
  532. else { //不满足条件执行
  533. y=x*x;
  534. cout<<"y="<<y; //输出结果
  535. }
  536. }
  537. #include <iostream.h>
  538. main()
  539. {
  540. int a,b,c;
  541. int smallest;
  542. cout<<"a b c"<<endl;
  543. cin>>a>>b>>c;
  544. if (a<=b) //外层条件语句
  545. {
  546. if (a<=c) //内层条件语句
  547. smallest=a;
  548. else
  549. smallest=c;
  550. }
  551. else
  552. {
  553. if (b<=c) //内层条件语句
  554. smallest=b;
  555. else
  556. smallest=c;
  557. }
  558. cout<<"Smallest="<<smallest<<endl;
  559. }
  560. #include <iostream.h>
  561. main()
  562. {
  563. int score;
  564. //从键盘上输入分数
  565. cout<<"score=";
  566. cin>>score;
  567. //用带else if的条件语句判断处理
  568. if (score<0 || score>100)
  569. {
  570. cout<<"The score is out of range!"<<endl;
  571. }
  572. else if (score>=90)
  573. cout<<"Your grade is a A."<<endl;
  574. else if (score>=80)
  575. cout<<"Your grade is a B."<<endl;
  576. else if (score>=70)
  577. cout<<"Your grade is a C."<<endl;
  578. else if (score>=60)
  579. cout<<"Your grade is a D."<<endl;
  580. else
  581. cout<<"Your grade is a E."<<endl;
  582. }
  583. #include <iostream.h>
  584. main()
  585. {
  586. int n;
  587. cout<<"n=";
  588. cin>>n;
  589. if (n>=0 && n<=100 &&n%2==0)
  590. cout<<"n="<<n<<endl;
  591. else
  592. cout<<"The "<<n<<" is out of range!"<<endl;
  593. }
  594. #include <iostream.h>
  595. main()
  596. {
  597. int a,b,Max;
  598. //输入数据
  599. cout<<"a=";
  600. cin>>a;
  601. cout<<"b=";
  602. cin>>b;
  603. //找出较大值
  604. Max=a>b?a:b;
  605. cout<<"Max="<<Max<<endl;
  606. }
  607. #include <iostream.h>
  608. main()
  609. {
  610. int a,b;
  611. //输入数据
  612. cout<<"a=";
  613. cin>>a;
  614. cout<<"b=";
  615. cin>>b;
  616. //除法判断
  617. if (b!=0 && a%b==0) {
  618. cout<<b<<" divides "<<a<<endl;
  619. cout<<"a/b="<<a/b<<endl;
  620. }
  621. else
  622. cout<<b<<" does not divide "<<a<<endl;
  623. }
  624. #include <iostream.h>
  625. main()
  626. {
  627. //x,y 为操作数,c为运算符
  628. int x,y,z;
  629. char c1;
  630. cin>>x>>c1>>y; //c1
  631. //多路选择语句选择不同表达式计算语句
  632. switch(c1) {
  633. case '+':cout<<x<<"+"<<y<<"="<<x+y<<endl;
  634. break;
  635. case '-':cout<<x<<"-"<<y<<"="<<x-y<<endl;
  636. break;
  637. case '*':cout<<x<<"*"<<y<<"="<<x*y<<endl;
  638. break;
  639. case '/':cout<<x<<"/"<<y<<"="<<x/y<<endl;
  640. break;
  641. case '%':cout<<x<<"%"<<y<<"="<<x%y<<endl;
  642. break;
  643. default :cout<<"Wrong !"<<endl; //当不符合上述情况时执行本子句
  644. }
  645. }
  646. #include<iostream.h>
  647. float x=365.5; //声明全局变量
  648. main() {
  649. int x=1,y=2;
  650. double w=x+y;
  651. {
  652. double x=1.414,y=1.732,z=3.14;
  653. cout<<"inner:x="<<x<<endl;
  654. cout<<"inner:y="<<y<<endl;
  655. cout<<"inner:z="<<z<<endl;
  656. cout<<"outer:w="<<w<<endl;
  657. cout<<"::x="<<::x<<endl; //访问重名的全局变量
  658. }
  659. cout<<"outer:x="<<x<<endl;
  660. cout<<"outer:y="<<y<<endl;
  661. cout<<"outer:w="<<w<<endl;
  662. //cout<<"inner:z="<<z<<endl;无效
  663. cout<<"::x="<<::x<<endl; //访问重名的全局变量
  664. }
  665. #include<iostream.h>
  666. main() {
  667. //显示1,2,3...10
  668. for(int i=1;i<=10;i++)
  669. cout<<i<<" ";
  670. cout<<endl;
  671. //显示10,9,8...1
  672. for(int j=10;j>=1;j--)
  673. cout<<j<<" ";
  674. cout<<endl;
  675. //显示1,3,5...9
  676. for(int k=1;k<=10;k=k+2)
  677. cout<<k<<" ";
  678. cout<<endl;
  679. //显示ABC...Z
  680. for(char c='A';c<='Z';c++)
  681. cout<<c;
  682. cout<<endl;
  683. //显示0,0.1,0.2...1.0
  684. for(float x=0;x<=1.0;x=x+0.1)
  685. cout<<x<<" ";
  686. cout<<endl;
  687. //显示0,0.1,0.2...1.0
  688. for(float x1=0;x1<=1.0+0.1/2;x1=x1+0.1)
  689. cout<<x1<<" ";
  690. cout<<endl;
  691. //计算s=1+2+3...+100
  692. int s=0;
  693. for(int n=1;n<=100;n++)
  694. s=s+n;
  695. cout<<"s="<<s<<endl;
  696. }
  697. #include<iostream.h>
  698. main()
  699. {
  700. //计算s=1+2+3...+100
  701. int s=0,n=1;
  702. while(n<=100) {
  703. s=s+n;
  704. n++;
  705. }
  706. cout<<"s="<<s<<endl;
  707. //累加键盘输入的数据
  708. double x,sum=0.0;
  709. cout<<"x=";
  710. cin>>x;
  711. while(x!=0) {
  712. sum+=x;
  713. cout<<"x=";
  714. cin>>x;
  715. }
  716. cout<<"sum="<<sum<<endl;
  717. }
  718. #include<iostream.h>
  719. main()
  720. {
  721. //计算s=1+2+3...+100
  722. int s=0,n=0;
  723. do {
  724. n++;
  725. s+=n;
  726. }while(n<100);
  727. cout<<"s="<<s<<endl;
  728. //累加键盘输入的数据
  729. double x,sum=0.0;
  730. do {
  731. cout<<"x=";
  732. cin>>x;
  733. sum+=x;
  734. } while(x!=0);
  735. cout<<"sum="<<sum<<endl;
  736. }
  737. #include<iostream.h>
  738. main()
  739. {
  740. //计算和打印打印乘法九九表
  741. for (int i=1;i<=9;i++) {
  742. cout<<i;
  743. for (int j=1;j<=9;j++)
  744. cout<<'\t'<<i<<"*"<<j<<"="<<i*j;
  745. cout<<endl;
  746. }
  747. }
  748. #include<iostream.h>
  749. main()
  750. {
  751. int x,sum=0;
  752. //定义标号L1
  753. L1: cout<<"x=";
  754. cin>>x;
  755. if (x==-1)
  756. goto L2; //无条件转移语句,转到L2语句处
  757. else
  758. sum+=x;
  759. goto L1; //无条件转移语句,转到L1语句处
  760. //定义标号L2
  761. L2: cout<<"sum="<<sum<<endl;
  762. }
  763. #include<iostream.h>
  764. main()
  765. {
  766. //累加键盘输入的数据
  767. double x,sum=0.0;
  768. while(1) {
  769. cout<<"x=";
  770. cin>>x;
  771. if (x<=0) break;
  772. sum+=x;
  773. }
  774. cout<<"sum="<<sum<<endl;
  775. }
  776. #include<iostream.h>
  777. main()
  778. {
  779. int i;
  780. for (i=1;i<=20;i++)
  781. {
  782. if (i%3==0) //能被 3 整除的整数,返回进行下次循环
  783. continue;
  784. cout<<i<<" ";
  785. }
  786. cout<<endl;
  787. }
  788. #include<iostream.h>
  789. main()
  790. {
  791. //声明数组和变量
  792. int a[5],i,sum;
  793. double avg;
  794. //从键盘上循环为数组赋值
  795. for (i=0;i<5;i++) {
  796. cout<<"a["<<i<<"]=";
  797. cin>>a[i];
  798. }
  799. //直接显示数组元素
  800. cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;
  801. //利用for循环显示数组各元素的值
  802. for (i=0;i<5;i++)
  803. cout<<a[i]<<" ";
  804. cout<<endl;
  805. //计算数组元素之和,并显示计算结果
  806. sum=a[0]+a[1]+a[2]+a[3]+a[4];
  807. cout<<"sum="<<sum<<endl;
  808. //利用循环计算数组的累加和
  809. for (sum=0,i=0;i<5;i++)
  810. sum+=a[i];
  811. //显示累加和及平均值
  812. cout<<"sum="<<sum<<endl;
  813. avg=sum/5.0;
  814. cout<<"avg="<<avg<<endl;
  815. }
  816. #include<iostream.h>
  817. main()
  818. {
  819. int i,max,index,a[5];
  820. //从键盘上为数组赋值
  821. for (i=0;i<=4;i++)
  822. {
  823. cout<<"a["<<i<<"]=";
  824. cin>>a[i];
  825. }
  826. // 利用循环遍历数组,找出最大值的元素及其下标
  827. max=a[0];
  828. for (i=0;i<=4;i++)
  829. {
  830. if (max<a[i])
  831. {
  832. max=a[i];
  833. index=i;
  834. }
  835. }
  836. cout<<"\nMax="<<max<<" index="<<index;
  837. }
  838. #include<iostream.h>
  839. #define size 5
  840. main()
  841. {
  842. //声明变量
  843. int i,j;
  844. float t,a[size];
  845. //从键盘上为数组赋值
  846. for (i=0;i<size;i++)
  847. {
  848. cout<<"a["<<i<<"]=";
  849. cin>>a[i];
  850. }
  851. //对数组按从小到大顺序排序
  852. for (i=0;i<size-1;i++)
  853. for (j=i+1;j<size;j++)
  854. if (a[i]>a[j])
  855. {
  856. t=a[i];
  857. a[i]=a[j];
  858. a[j]=t;
  859. }
  860. //显示排序结果
  861. for (i=0;i<size;i++)
  862. cout<<a[i]<<" ";
  863. cout<<endl;
  864. //输入要查找的数据
  865. int value;
  866. int found; //找到为1,否则为0
  867. int low,high,mid;
  868. for (i=1;i<=3;i++) {
  869. cout<<"value=";
  870. cin>>value;
  871. //二分法查找数组a
  872. found=0;
  873. low=0;
  874. high=size-1;
  875. while(low<=high)
  876. {
  877. mid=(high+low)/2;
  878. if (a[mid]==value)
  879. {
  880. found=1;
  881. break;
  882. }
  883. if (a[mid]<value)
  884. low=mid+1;
  885. else
  886. high=mid-1;
  887. }
  888. if (found)
  889. cout<<"The valu found at:a["<<mid<<"]="<<a[mid]<<endl;
  890. else
  891. cout<<"The "<<value<<" is not found!"<<endl;
  892. }
  893. }
  894. #include<iostream.h>
  895. main()
  896. {
  897. //声明变量
  898. int i,j;
  899. float t,a[5];
  900. //从键盘上为数组赋值
  901. for (i=0;i<=4;i++)
  902. {
  903. cout<<"a["<<i<<"]=";
  904. cin>>a[i];
  905. }
  906. //对数组按从大到小顺序排序
  907. for (i=0;i<=3;i++)
  908. for (j=i+1;j<=4;j++)
  909. if (a[i]<=a[j])
  910. {
  911. t=a[i];
  912. a[i]=a[j];
  913. a[j]=t;
  914. }
  915. //显示排序结果
  916. for (i=0;i<=4;i++)
  917. cout<<a[i]<<" ";
  918. }
  919. #include<iostream.h>
  920. main()
  921. {
  922. //声明二维数组及变量
  923. int a[2][3],i,j;
  924. //从键盘上为数组a赋值
  925. for (i=0;i<2;i++)
  926. for (j=0;j<3;j++)
  927. {
  928. cout<<"a["<<i<<"]["<<j<<"]=";
  929. cin>>a[i][j];
  930. }
  931. //显示数组a
  932. for (i=0;i<2;i++) {
  933. for (j=0;j<3;j++)
  934. {
  935. cout<<a[i][j]<<" ";
  936. }
  937. cout<<endl;
  938. }
  939. //找出该数组的最大元素及其下标
  940. int h,l,Max=a[0][0];
  941. for (i=0;i<2;i++) {
  942. for (j=0;j<3;j++)
  943. {
  944. if (Max<a[i][j]) {
  945. Max=a[i][j];
  946. h=i;
  947. l=j;
  948. }
  949. }
  950. }
  951. cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl;
  952. }
  953. #include<iostream.h>
  954. main()
  955. {
  956. //声明字符数组和变量
  957. char str[6];
  958. int i;
  959. //从键盘上输入字符串
  960. cout<<"str=";
  961. cin>>str;
  962. cout<<str<<endl;
  963. //按数组和下标变量两种方式显示字符数组
  964. cout<<str<<endl;
  965. for (i=0;i<6;i++)
  966. cout<<str[i];
  967. cout<<endl;
  968. //字符串反向输出
  969. for (i=5;i>=0;i--)
  970. cout<<str[i];
  971. cout<<endl;
  972. //将字符数组变成大写字母后输出
  973. for (i=0;i<=5;i++)
  974. str[i]-=32; //小写字母转换成大写字母
  975. cout<<str<<endl; //显示字符串
  976. }
  977. #include<iostream.h>
  978. main()
  979. {
  980. //声明变量和指针变量
  981. int a,b,c,*ip;
  982. //指针变量ip指向变量a
  983. a=100;
  984. ip=&a; //使指针变量 ip 指向变量a
  985. cout<<"a="<<a<<endl;
  986. cout<<"*ip="<<*ip<<endl;
  987. cout<<"ip="<<ip<<endl;
  988. //指针变量ip指向变量b
  989. ip=&b; //使指针变量 ip 指向变量b
  990. b=200;
  991. cout<<"b="<<b<<endl;
  992. cout<<"*ip="<<*ip<<endl;
  993. cout<<"ip="<<ip<<endl;
  994. //指针变量ip指向变量c
  995. ip=&c; //使指针变量 ip 指向变量b
  996. *ip=a+b;
  997. cout<<"c="<<c<<endl;
  998. cout<<"*ip="<<*ip<<endl;
  999. cout<<"ip="<<ip<<endl;
  1000. }
  1001. #include<iostream.h>
  1002. main()
  1003. {
  1004. //声明数组、变量和指针变量
  1005. int a[2][3],i,j;
  1006. int* ip;
  1007. //从键盘上为数组a赋值
  1008. for (i=0;i<2;i++) //为数组a赋值
  1009. for (j=0;j<3;j++)
  1010. {
  1011. cout<<"a["<<i<<"]["<<j<<"]=";
  1012. cin>>a[i][j];
  1013. }
  1014. //利用下标变量显示数组a
  1015. for (i=0;i<2;i++) {
  1016. for (j=0;j<3;j++)
  1017. {
  1018. cout<<a[i][j]<<" ";
  1019. }
  1020. cout<<endl;
  1021. }
  1022. //利用指针变量显示数组a
  1023. ip=&a[0][0];
  1024. for (i=0;i<2;i++) {
  1025. for (j=0;j<3;j++)
  1026. {
  1027. cout<<"a["<<i<<"]["<<j<<"]=";
  1028. cout<<ip<<" ";
  1029. cout<<*ip<<endl;
  1030. ip++;
  1031. }
  1032. }
  1033. }
  1034. #include<iostream.h>
  1035. main()
  1036. {
  1037. //声明数组、变量和指针变量
  1038. int a[]={1,2,3,4,5,6};
  1039. int *ip1,*ip2;
  1040. //测试指针的赋值运算
  1041. ip1=a;
  1042. ip2=ip1;
  1043. cout<<"*ip1="<<(*ip1)<<endl;
  1044. cout<<"*ip2="<<(*ip2)<<endl;
  1045. //测试指针的自增自减运算和组合运算
  1046. ip1++;
  1047. ip2+=4;
  1048. cout<<"*ip1="<<(*ip1)<<endl;
  1049. cout<<"*ip2="<<(*ip2)<<endl;
  1050. //测试指针变量之间的关系运算
  1051. int n=ip2>ip1;
  1052. cout<<"ip2>ip1="<<n<<endl;
  1053. cout<<"ip2!=NULL="<<(ip2!=NULL)<<endl;
  1054. //指针变量之间的减法
  1055. n=ip2-ip1;
  1056. cout<<"ip2-ip1="<<n<<endl;
  1057. }
  1058. #include<iostream.h>
  1059. main()
  1060. {
  1061. //声明字符型数组和指针变量
  1062. char str[10];
  1063. char *strip=str;
  1064. //输入输出
  1065. cout<<"str=";
  1066. cin>>str; //用字符数组输入字符串
  1067. cout<<"str="<<str<<endl;
  1068. cout<<"strip="<<strip<<endl;
  1069. cout<<"strip=";
  1070. cin>>strip; //用字符指针变量输入字符串
  1071. cout<<"str="<<str<<endl;
  1072. cout<<"strip="<<strip<<endl;
  1073. //利用指针变量改变其指向字符串的内容
  1074. *(strip+2)='l';
  1075. cout<<"str="<<str<<endl;
  1076. cout<<"strip="<<strip<<endl;
  1077. //动态为字符型指针变量分配内存
  1078. strip=new char(100);
  1079. cout<<"strip=";
  1080. cin>>strip; //用字符指针变量输入字符串
  1081. cout<<"str="<<str<<endl;
  1082. cout<<"strip="<<strip<<endl;
  1083. }
  1084. #include<iostream.h>
  1085. main()
  1086. {
  1087. // 声明用于存放运动员号码的数组
  1088. int h[]={1001,1002,1003,1004};
  1089. // 声明用于存放运动员成绩的数组
  1090. float x[]={12.3,13.1,11.9,12.1};
  1091. //声明用于存放运动姓名的字符型指针数组
  1092. char *p[]={"Wang hua","Zhang jian","Li wei","Hua ming"};
  1093. //i,j,it是用做循环控制变量和临时变量
  1094. int i,j,it;
  1095. //ft 用做暂存变量
  1096. float ft;
  1097. //pt为字符型指针变量用做暂存指针变量
  1098. char *pt;
  1099. //用选择法对数组x进行排序,并相应调整数组h和p中的数据
  1100. for (i=0;i<=3;i++)
  1101. for (j=i+1;j<=3;j++)
  1102. if (x[i]>=x[j]) {
  1103. ft=x[i],x[i]=x[j],x[j]=ft;
  1104. it=h[i],h[i]=h[j],h[j]=it;
  1105. pt=p[i],p[i]=p[j],p[j]=pt;
  1106. }
  1107. //以下打印排序结果
  1108. for (i=0;i<=3;i++)
  1109. cout<<h[i]<<" ,"<<p[i]<<" ,"<<x[i]<<endl;
  1110. }
  1111. #include<iostream.h>
  1112. main()
  1113. {
  1114. //声明指针数组
  1115. char *colors[]={"Red","Blue","Yellow","Green"};
  1116. //指向指针的指针变量
  1117. char **pt;
  1118. //通过指向指针的变量访问其指向的内容
  1119. pt=colors;
  1120. for (int i=0;i<=3;i++) {
  1121. cout<<"pt="<<pt<<endl;
  1122. cout<<"*pt="<<*pt<<endl;
  1123. cout<<"**pt="<<**pt<<endl;
  1124. pt++;
  1125. }
  1126. }
  1127. #include<iostream.h>
  1128. main()
  1129. {
  1130. //定义结构类型
  1131. struct books
  1132. {
  1133. char title[20];
  1134. char author[15];
  1135. int pages;
  1136. float price;
  1137. } ;
  1138. //声明结构变量
  1139. struct books Zbk={"VC++ ","Zhang",295,35.5};
  1140. books Wbk;
  1141. //对结构变量的输出
  1142. cout<<"Zbk:"<<endl;
  1143. cout<<Zbk.title <<endl;
  1144. cout<<Zbk.author<<endl;
  1145. cout<<Zbk.pages<<endl;
  1146. cout<<Zbk.price<<endl;
  1147. cout<<"--------------------"<<endl;
  1148. //对结构成员的运算
  1149. Zbk.pages+=10;
  1150. Zbk.price+=0.5;
  1151. cout<<"Zbk.pages="<<Zbk.pages<<endl;
  1152. cout<<"Zbk.price="<<Zbk.price<<endl;
  1153. cout<<"--------------------"<<endl;
  1154. //对结构变量的输入输出
  1155. cout<<"Wbk.title =";
  1156. cin>>Wbk.title;
  1157. cout<<"Wbk.author=";
  1158. cin>>Wbk.author;
  1159. cout<<"Wbk.pages=";
  1160. cin>>Wbk.pages;
  1161. cout<<"Wbk.price=";
  1162. cin>>Wbk.price;
  1163. cout<<"Wbk:"<<endl;
  1164. cout<<Wbk.title <<endl;
  1165. cout<<Wbk.author<<endl;
  1166. cout<<Wbk.pages<<endl;
  1167. cout<<Wbk.price<<endl;
  1168. cout<<"--------------------"<<endl;
  1169. //结构变量之间的相互赋值
  1170. books temp;
  1171. temp=Wbk;
  1172. cout<<"temp:"<<endl;
  1173. cout<<temp.title<<endl;
  1174. cout<<temp.author<<endl;
  1175. cout<<temp.pages<<endl;
  1176. cout<<temp.price<<endl;
  1177. }
  1178. #include<iostream.h>
  1179. main()
  1180. {
  1181. int i;
  1182. //定义结构类型
  1183. struct student {
  1184. int num;
  1185. char name[10];
  1186. float maths;
  1187. float physics;
  1188. float chemistry;
  1189. double total;
  1190. };
  1191. //声明结构数组st
  1192. student st[3];
  1193. //从键盘上为结构数组输入值
  1194. cout<<" num name maths physics chemistry "<<endl;
  1195. for (i=0;i<3;i++)
  1196. {
  1197. cout<<i+1<<" ";
  1198. cin>>st[i].num;
  1199. cin>>st[i].name;
  1200. cin>>st[i].maths;
  1201. cin>>st[i].physics;
  1202. cin>>st[i].chemistry;
  1203. }
  1204. //计算每个学生的总成绩
  1205. for (i=0;i<3;i++)
  1206. st[i].total=st[i].maths+st[i].physics+st[i].chemistry;
  1207. //输出结构数组各元素的值
  1208. for (i=0;i<3;i++)
  1209. {
  1210. cout<<"st["<<i<<"]: ";
  1211. cout<<st[i].num<<'\t';
  1212. cout<<st[i].name<<'\t';
  1213. cout<<st[i].maths<<'\t';
  1214. cout<<st[i].physics<<'\t';
  1215. cout<<st[i].chemistry<<'\t';
  1216. cout<<st[i].total<<endl;
  1217. }
  1218. }
  1219. #include<iostream.h>
  1220. main()
  1221. {
  1222. //定义结构类型
  1223. struct human {
  1224. char name[10];
  1225. int sex;
  1226. int age;
  1227. };
  1228. //声明结构变量和结构指针变量,并初始化
  1229. struct human x={"WangPing",1,30},*p=NULL;
  1230. //结构指针变量指向对象
  1231. p=&x;
  1232. //显示结构变量的值
  1233. cout<<"x.name="<<x.name<<endl;
  1234. cout<<"x.sex="<<x.sex<<endl;
  1235. cout<<"x.age="<<x.age<<endl;
  1236. //利用结构指针显示结构对象中的数据
  1237. cout<<"(*p).name="<<(*p).name<<endl;
  1238. cout<<"(*p).sex="<<(*p).sex<<endl;
  1239. cout<<"(*p).age="<<(*p).age<<endl;
  1240. cout<<"p->name="<<p->name<<endl;
  1241. cout<<"p->sex="<<p->sex<<endl;
  1242. cout<<"p->age="<<p->age<<endl;
  1243. //通过结构指针为结构对象输入数据
  1244. cout<<"name:";
  1245. cin>>(*p).name;
  1246. cout<<"sex:";
  1247. cin>>(*p).sex;
  1248. cout<<"age:";
  1249. cin>>(*p).age;
  1250. //显示结构变量的值
  1251. cout<<"x.name="<<x.name<<endl;
  1252. cout<<"x.sex="<<x.sex<<endl;
  1253. cout<<"x.age="<<x.age<<endl;
  1254. }
  1255. include<iostream.h>
  1256. main()
  1257. {
  1258. //定义结构类型
  1259. struct human {
  1260. char name[10];
  1261. int sex;
  1262. int age;
  1263. };
  1264. //声明结构变量和结构指针,并初始化
  1265. struct human x={"WangPing",1,30},*p=&x;
  1266. //利用结构指针显示结构中的数据
  1267. cout<<"(*p).name="<<(*p).name<<endl;
  1268. cout<<"(*p).sex="<<(*p).sex<<endl;
  1269. cout<<"(*p).age="<<(*p).age<<endl;
  1270. cout<<"-------------------------"<<endl;
  1271. //利用new运算符为p分配内存
  1272. p=new human;
  1273. //从键盘上为p指向的结构对象赋值
  1274. cout<<"p->name=";
  1275. cin>>p->name;
  1276. cout<<"p->sex=";
  1277. cin>>p->sex;
  1278. cout<<"p->age=";
  1279. cin>>p->age;
  1280. cout<<"-------------------------"<<endl;
  1281. //显示p所指结构对象的值
  1282. cout<<"p->name="<<p->name<<endl;
  1283. cout<<"p->sex="<<p->sex<<endl;
  1284. cout<<"p->age="<<p->age<<endl;
  1285. cout<<"-------------------------"<<endl;
  1286. //显示结构变量的值
  1287. cout<<"x.name="<<x.name<<endl;
  1288. cout<<"x.sex="<<x.sex<<endl;
  1289. cout<<"x.age="<<x.age<<endl;
  1290. //释放p指向的内存
  1291. delete p;
  1292. }
  1293. #include<iostream.h>
  1294. main()
  1295. {
  1296. //定义结构类型
  1297. struct human {
  1298. char name[10];
  1299. int sex;
  1300. int age;
  1301. };
  1302. //声明结构数组和结构指针变量,并初始化
  1303. human x[]={{"WeiPing",1,30},{"LiHua",1,25},{"LiuMin",0,23}},*p=NULL;
  1304. //用下标变量的输出结构数组的元素
  1305. for (int i=0;i<3;i++)
  1306. {
  1307. cout<<x[i].name<<'\t';
  1308. cout<<x[i].sex<<'\t';
  1309. cout<<x[i].age<<endl;
  1310. }
  1311. cout<<"----------------"<<endl;
  1312. //用结构指针输出结构数组的元素
  1313. for (p=x;p<=&x[2];p++)
  1314. {
  1315. cout<<p->name<<'\t';
  1316. cout<<p->sex<<'\t';
  1317. cout<<p->age<<endl;
  1318. }
  1319. }
  1320. #include<iostream.h>
  1321. main()
  1322. {
  1323. //定义一个包含指针成员的结构类型
  1324. struct test {
  1325. char *str;
  1326. int *ip;
  1327. } x;
  1328. //使用结构变量x中的整型指针ip
  1329. x.ip=new int; //分配1个单元
  1330. *(x.ip)=100;
  1331. cout<<"x.ip:"<<x.ip<<'\t'<<*(x.ip)<<endl;
  1332. cout<<"---------------"<<endl;
  1333. delete x.ip;
  1334. x.ip=new int[5]; //分配5个单元
  1335. for(int i=0;i<5;i++)
  1336. *(x.ip+i)=100+i;
  1337. cout<<"x.ip:"<<endl;
  1338. for(i=0;i<5;i++)
  1339. cout<<x.ip+i<<'\t'<<(*(x.ip+i))<<endl;
  1340. delete x.ip;
  1341. cout<<"---------------"<<endl;
  1342. //使用结构变量x中的字符型指针str
  1343. x.str=new char('A'); //分配1个单元
  1344. cout<<"x.str:"<<(*x.str)<<endl;
  1345. cout<<"---------------"<<endl;
  1346. delete x.str;
  1347. x.str=new char[5]; //分配多个单元
  1348. *x.str='G';
  1349. *(x.str+1)='o';
  1350. *(x.str+2)='o';
  1351. *(x.str+3)='d';
  1352. *(x.str+4)='\0';
  1353. cout<<"x.str:"<<x.str<<endl;
  1354. delete x.str;
  1355. cout<<"---------------"<<endl;
  1356. //在声明结构变量时初始化
  1357. test y={"Very Good!",NULL};
  1358. cout<<"y.str:"<<y.str<<endl;
  1359. cout<<"y.ip:"<<y.ip<<endl;
  1360. }
  1361. #include<iostream.h>
  1362. main()
  1363. {
  1364. //定义date结构
  1365. struct date
  1366. {
  1367. int year;
  1368. int month;
  1369. int day;
  1370. };
  1371. //定义baby结构
  1372. struct baby {
  1373. int num;
  1374. float weight;
  1375. date birthday; // date为结构类型
  1376. };
  1377. //声明baby结构变量并初始化
  1378. baby b1={10001,10,{2002,12,25}};
  1379. //下列是baby结构变量b1的引用。
  1380. cout<<"b1.num="<<b1.num<<endl;
  1381. cout<<"b1.weight="<<b1.weight<<endl;
  1382. cout<<"b1.birthday.year="<<b1.birthday.year<<endl;
  1383. cout<<"b1.birthday.month="<<b1.birthday.month<<endl;
  1384. cout<<"b1.birthday.day="<<b1.birthday.day<<endl;
  1385. cout<<"--------------------------"<<endl;
  1386. //声明baby结构变量temp,并进行赋值运算
  1387. baby temp;
  1388. temp=b1;
  1389. cout<<"temp.num="<<temp.num<<endl;
  1390. cout<<"temp.weight="<<temp.weight<<endl;
  1391. cout<<"temp.birthday.year="<<temp.birthday.year<<endl;
  1392. cout<<"temp.birthday.month="<<temp.birthday.month<<endl;
  1393. cout<<"temp.birthday.day="<<temp.birthday.day<<endl;
  1394. }
  1395. #include<iostream.h>
  1396. main()
  1397. {
  1398. //定义名为list的递归结构
  1399. struct list {
  1400. char name[10];
  1401. int sex;
  1402. int age;
  1403. list *next; //成员next为指向其自身结构的指针
  1404. };
  1405. //使用递归结构变量
  1406. list L1={"WeiPing",1,35.5,NULL};
  1407. cout<<"L1:"<<endl;
  1408. cout<<"name\t"<<L1.name<<endl;
  1409. cout<<"sex\t"<<L1.sex<<endl;
  1410. cout<<"age\t"<<L1.age<<endl;
  1411. cout<<"next\t"<<L1.next<<endl;
  1412. }
  1413. #include<iostream.h>
  1414. main()
  1415. {
  1416. int i;
  1417. //定义名为student的递归结构
  1418. struct student {
  1419. char name[10];
  1420. int math;
  1421. int computer;
  1422. float sum;
  1423. student *next; //next成员是指向自身的结构指针
  1424. };
  1425. //用student声明3个结构指针变量
  1426. struct student *head,*tail,*temp;
  1427. //申请第1块数据,并设置各结构指针的初值
  1428. temp=new struct student; //申请内存
  1429. head=temp; // 头指针
  1430. tail=head; // 尾指针
  1431. //循环为链表输入数据
  1432. cout<<"\tname Math Computer"<<endl;
  1433. for (i=1;;i++) {
  1434. cout<<i<<"\t";
  1435. cin>>temp->name;
  1436. if (temp->name[0]!='*')
  1437. {
  1438. cin>>temp->math>>temp->computer;
  1439. temp->sum=temp->math+temp->computer;
  1440. temp->next=NULL;
  1441. tail=temp; //设置链表尾指针
  1442. }
  1443. else
  1444. {
  1445. // 以下是输入结束处理
  1446. delete temp;
  1447. tail->next=NULL;
  1448. break;
  1449. }
  1450. //为下一个学生申请内存
  1451. temp->next=new struct student;
  1452. temp=temp->next; // 使处理指针temp指向新内存块
  1453. }
  1454. //将链表数据从头到尾打印出来
  1455. cout<<"--------------------"<<endl;
  1456. temp=head;
  1457. while (temp!=NULL) {
  1458. cout<<temp->name<<","<<temp->math<<",";
  1459. cout<<temp->computer<<","<<temp->sum<<endl;
  1460. temp=temp->next;
  1461. }
  1462. }
  1463. #include<iostream.h>
  1464. main()
  1465. {
  1466. int i;
  1467. //定义名为student的递归结构
  1468. struct student {
  1469. char name[10];
  1470. int math;
  1471. int computer;
  1472. float sum;
  1473. student *forw; //forw成员是前指针
  1474. student *next; //next成员是后指针
  1475. };
  1476. //用student声明3个结构指针变量
  1477. struct student *head,*tail,*temp;
  1478. //申请第1块数据,并设置各结构指针的初值
  1479. temp=new struct student; //申请内存
  1480. head=temp; // 头指针
  1481. tail=head; // 尾指针
  1482. head->forw=NULL;
  1483. //循环为链表记录输入数据
  1484. cout<<"\tname Math Computer"<<endl;
  1485. for (i=1;;i++) {
  1486. cout<<i<<"\t";
  1487. cin>>temp->name;
  1488. if (temp->name[0]!='*')
  1489. {
  1490. cin>>temp->math>>temp->computer;
  1491. temp->sum=temp->math+temp->computer;
  1492. temp->next=NULL;
  1493. tail=temp; //设置链表尾指针
  1494. }
  1495. else
  1496. {
  1497. // 以下是输入结束处理
  1498. delete temp;
  1499. tail->next=NULL;
  1500. break;
  1501. }
  1502. //为下一个学生申请内存
  1503. temp->next=new struct student;
  1504. temp->next->forw=temp; //设置前指针
  1505. temp=temp->next; //使处理指针temp指向新内存块
  1506. }
  1507. // 将链表数据从头到尾打印出来
  1508. cout<<"head------>tail:"<<endl;
  1509. temp=head;
  1510. while (temp!=NULL) {
  1511. cout<<temp->name<<","<<temp->math<<",";
  1512. cout<<temp->computer<<","<<temp->sum<<endl;
  1513. temp=temp->next;
  1514. }
  1515. // 将链表数据从尾到头打印出来
  1516. cout<<"tail------>head:"<<endl;
  1517. temp=tail;
  1518. while (temp!=NULL) {
  1519. cout<<temp->name<<","<<temp->math<<",";
  1520. cout<<temp->computer<<","<<temp->sum<<endl;
  1521. temp=temp->forw;
  1522. }
  1523. }
  1524. #include<iostream.h>
  1525. main()
  1526. {
  1527. int i;
  1528. //定义联合类型
  1529. union utag {
  1530. char c;
  1531. int k;
  1532. float x;
  1533. };
  1534. //声明联合变量
  1535. union utag u;
  1536. // 使用联合变量中的字符型成员
  1537. u.c='*';
  1538. cout<<"u.c="<<u.c<<endl;
  1539. // 使用联合变量中的整型成员
  1540. u.k=1000;
  1541. cout<<"u.k="<<u.k<<endl;
  1542. // 使用联合变量中的浮点型成员
  1543. u.x=3.1416;
  1544. cout<<"u.x="<<u.x<<endl;
  1545. //声明联合变量时初始化
  1546. utag u1={'A'};
  1547. //同时引用联合变量的各成员
  1548. cout<<"u1.c="<<u1.c<<endl;
  1549. cout<<"u1.k="<<u1.k<<endl;
  1550. cout<<"u1.x="<<u1.x<<endl;
  1551. }
  1552. #include<iostream.h>
  1553. main()
  1554. {
  1555. //定义结构类型,并为声明的结构变量赋初值
  1556. struct s_tag {
  1557. short i;
  1558. float x;
  1559. } sx={100,3.1416};
  1560. //定义联合类型,并为声明的联合变量赋初值
  1561. union u_tag {
  1562. short i;
  1563. float x;
  1564. } ux={1000};
  1565. //输出结构类型和结构变量的有关信息
  1566. cout<<"sizeof(struct s_tag)="<<sizeof(struct s_tag)<<endl;
  1567. cout<<"sx.i="<<sx.i<<endl;
  1568. cout<<"sx.x="<<sx.x<<endl;
  1569. cout<<"sizeof(sx)="<<sizeof(sx)<<endl;
  1570. cout<<"------------------------------"<<endl;
  1571. //输出联合类型和联合变量的有关信息
  1572. cout<<"sizeof(union u_tag)="<<sizeof(union u_tag)<<endl;
  1573. ux.i=200;
  1574. cout<<"ux.i="<<ux.i<<endl; //输出联合变量ux 的i成员
  1575. ux.x=123.456;
  1576. cout<<"ux.x="<<ux.x<<endl; //输出联合变量ux 的x成员
  1577. cout<<"sizeof(ux)="<<sizeof(ux)<<endl;
  1578. }
  1579. #include<iostream.h>
  1580. main()
  1581. {
  1582. //自定义类型
  1583. typedef int ARRAY_INT[50];
  1584. int i;
  1585. ARRAY_INT a; //用自定义类型声明数组变量a
  1586. //以下为数组a赋值,并打印
  1587. for (i=0;i<50;i++) {
  1588. if (i%10==0) //每10个数换一次行
  1589. cout<<endl;
  1590. a[i]=i;
  1591. cout<<a[i]<<"\t";
  1592. }
  1593. cout<<endl;
  1594. }
  1595. #include<iostream.h>
  1596. //定义结构类型
  1597. struct student
  1598. {
  1599. int num;
  1600. char name[20];
  1601. float grade;
  1602. };
  1603. void main(void)
  1604. {
  1605. //声明数组
  1606. int i,size;
  1607. char str[]="This is a string.";
  1608. int int_values[] = {51, 23, 2, 44, 45,0,11};
  1609. float float_values[] = {15.1, 13.3, 22.2, 10.4, 1.5};
  1610. student st_arr[]={101,"WangLin",92,102,"LiPing",85,103,"ZhaoMin",88};
  1611. //显示char类型数组元素及其大小
  1612. size=sizeof(str) / sizeof(char);
  1613. cout<<"Number of elements in str: ";
  1614. cout<<size<<endl;
  1615. for(i=0;i<size;i++) {
  1616. cout<<str[i];
  1617. }
  1618. cout<<endl;
  1619. //显示int类型数组元素及其大小
  1620. size=sizeof(int_values) / sizeof(int);
  1621. cout<<"Number of elements in int_values: ";
  1622. cout<<size<<endl;
  1623. for(i=0;i<size;i++) {
  1624. cout<<int_values[i]<<" ";
  1625. }
  1626. cout<<endl;
  1627. //显示float类型数组元素及其大小
  1628. size=sizeof(float_values) / sizeof(float);
  1629. cout<<"Number of elements in float_values: ";
  1630. cout<<size<<endl;
  1631. for(i=0;i<size;i++) {
  1632. cout<<float_values[i]<<" ";
  1633. }
  1634. cout<<endl;
  1635. //显示student类型数组元素及其大小
  1636. size=sizeof(st_arr) / sizeof(student);
  1637. cout<<"Number of elements in st_arr: ";
  1638. cout<<size<<endl;
  1639. for(i=0;i<size;i++) {
  1640. cout<<st_arr[i].num<<" ";
  1641. cout<<st_arr[i].name<<" ";
  1642. cout<<st_arr[i].grade<<endl;
  1643. }
  1644. }
  1645. #include<iostream.h>
  1646. //add()函数的定义,其有返回值
  1647. double add(double x,double y)
  1648. {
  1649. double z;
  1650. z=x+y;
  1651. cout<<x<<"+"<<y<<"="<<z<<endl;
  1652. return(z);
  1653. }
  1654. main()
  1655. {
  1656. double a=0.5,b=1.0;
  1657. //以不同参数形式调用函数add()
  1658. cout<<"add(1.5,2.5)="<<add(1.5,2.5)<<endl;
  1659. cout<<"add(a,b)="<<add(a,b)<<endl;
  1660. cout<<"add(2*a,a+b)="<<add(2*a,a+b)<<endl;
  1661. cout<<"----------------------"<<endl;
  1662. //以表达式方式调用函数add()
  1663. double c=2*add(a,b);
  1664. cout<<"c="<<c<<endl;
  1665. cout<<"----------------------"<<endl;
  1666. //以语句式方式调用函数add()
  1667. add(2*a,b);
  1668. cout<<"----------------------"<<endl;
  1669. //用其他类型参数调用函数add()
  1670. int n=1,m=2;
  1671. cout<<"add("<<n<<","<<m<<")="<<add(n,m)<<endl;
  1672. }
  1673. #include<iostream.h>
  1674. //定义符号函数sgn(),其返回值为int类型
  1675. int sgn(double x)
  1676. {
  1677. if (x>0) return(1); //返回出口1
  1678. if (x<0) return(-1); //返回出口2
  1679. return(0); //返回出口3
  1680. }
  1681. //main()函数定义
  1682. main()
  1683. {
  1684. double x;
  1685. int i;
  1686. for (i=0;i<=2;i++) {
  1687. cout<<"x=";
  1688. cin>>x;
  1689. cout<<"sgn("<<x<<")="<<sgn(x)<<endl;
  1690. }
  1691. }
  1692. #include<iostream.h>
  1693. //函数原型语句可以在这里
  1694. //定义main()函数
  1695. main()
  1696. {
  1697. //max()函数原型声明语句
  1698. float max(float,float);
  1699. //变量声明语句
  1700. float a,b,Max;
  1701. //输入参数并计算
  1702. cout<<"a=";
  1703. cin>>a;
  1704. cout<<"b=";
  1705. cin>>b;
  1706. Max=max(a,b); //调用max()函数
  1707. cout<<"max("<<a<<","<<b<<")="<<Max<<endl;
  1708. }
  1709. //定义max()函数
  1710. float max(float x,float y) //max()返回值类型为浮点型
  1711. {
  1712. float z;
  1713. z=(x>y)?x:y;
  1714. return(z);
  1715. }
  1716. #include<iostream.h>
  1717. //定义f()函数
  1718. f(int x,int y) //f()的参数以值方式传递
  1719. {
  1720. ++x;
  1721. --y;
  1722. cout<<"x="<<x<<",y="<<y<<endl;
  1723. }
  1724. main() {
  1725. int a,b;
  1726. //设置实际参数的值
  1727. a=b=10;
  1728. //以变量为参数调用f()函数
  1729. f(a,b);
  1730. //验证实际参数的值
  1731. cout<<"a="<<a<<",b="<<b<<endl;
  1732. //以表达式参数形式调用f()函数
  1733. f(2*a,a+b);
  1734. }
  1735. #include<iostream.h>
  1736. //定义公共结构类型
  1737. struct student {
  1738. int num;
  1739. char name[10];
  1740. float maths;
  1741. float physics;
  1742. float chemistry;
  1743. double total;
  1744. };
  1745. //定义结构输入函数
  1746. input_Rec(struct student *p) //参数为student类型的结构指针变量
  1747. {
  1748. cin>>p->num;
  1749. cin>>p->name;
  1750. cin>>p->maths;
  1751. cin>>p->physics;
  1752. cin>>p->chemistry;
  1753. }
  1754. //定义结构数据交换函数
  1755. swap_Rec(struct student *p1,struct student *p2)
  1756. {
  1757. struct student x;
  1758. //交换两个记录的数据
  1759. x=*p1;
  1760. *p1=*p2;
  1761. *p2=x;
  1762. }
  1763. //输出结构的值
  1764. put_Rec(struct student *p)
  1765. {
  1766. cout<<p->num<<'\t';
  1767. cout<<p->name<<'\t';
  1768. cout<<p->maths<<'\t';
  1769. cout<<p->physics<<'\t';
  1770. cout<<p->chemistry<<'\t';
  1771. cout<<p->total<<endl;
  1772. }
  1773. //定义main()函数
  1774. main()
  1775. {
  1776. int i,j;
  1777. // 声明结构指针变量和结构数组
  1778. struct student *p1,a[3];
  1779. //输入3个学生的数据并计算总成绩
  1780. cout<<"num\tname\tmaths\tphysics\tchemistry"<<endl;
  1781. for (p1=a;p1<=a+2;p1++) {
  1782. input_Rec(p1);
  1783. p1->total=p1->maths+p1->physics+p1->chemistry;
  1784. }
  1785. //对3个学生的数据排序
  1786. for (i=0;i<=2;i++)
  1787. for (j=i+1;j<=2;j++)
  1788. if (a[i].total<a[j].total)
  1789. swap_Rec(&a[i],&a[j]); //交换两个结构变量中的数据
  1790. cout<<"-------------------"<<endl; //输出一分界线
  1791. //输出排序后的结构数组
  1792. cout<<"num\tname\tmaths\tphysics\tchemistry\ttotal"<<endl;
  1793. for (p1=a;p1<=a+2;p1++)
  1794. put_Rec(p1);
  1795. }
  1796. #include<iostream.h>
  1797. //定义结构
  1798. struct student {
  1799. char name[10];
  1800. float grade;
  1801. };
  1802. //交换student类型的数据
  1803. void swap(student &x,student &y) //swap的参数为引用传递方式
  1804. {
  1805. student temp;
  1806. temp=x;
  1807. x=y;
  1808. y=temp;
  1809. }
  1810. //返回student类型的引用,求优者
  1811. student& max(student &x,student &y) //swap的参数为引用传递方式
  1812. {
  1813. return (x.grade>y.grade?x:y);
  1814. }
  1815. //显示student类型的数据
  1816. void show(student &x) //show的参数为引用传递方式
  1817. {
  1818. cout<<x.name<<" "<<x.grade<<endl;
  1819. }
  1820. void main()
  1821. {
  1822. student a={"ZhangHua",351.5},b={"WangJun",385};
  1823. //显示a和b的数据
  1824. cout<<"a:";
  1825. show(a);
  1826. cout<<"b:";
  1827. show(b);
  1828. cout<<"------------------"<<endl;
  1829. //交换a和b的数据,并显示
  1830. swap(a,b);
  1831. cout<<"a:";
  1832. show(a);
  1833. cout<<"b:";
  1834. show(b);
  1835. cout<<"------------------"<<endl;
  1836. //计算和显示成绩高者
  1837. student t=max(a,b);
  1838. cout<<"Max:";
  1839. show(t);
  1840. }
  1841. #include <iostream.h>
  1842. //参数带有默认值的函数
  1843. disp(int x=1,int y=1,int z=1)
  1844. {
  1845. cout<<"参数1: "<<x<<endl;
  1846. cout<<"参数2: "<<y<<endl;
  1847. cout<<"参数3: "<<z<<endl;
  1848. cout<<"------------------"<<endl;
  1849. }
  1850. //main()函数中测试参数带有默认值的函数disp()
  1851. void main()
  1852. {
  1853. disp();
  1854. disp(10);
  1855. disp(10,20);
  1856. disp(10,20,30);
  1857. int a=1,b=2,c=3;
  1858. disp(a,b,c);
  1859. }
  1860. #include <iostream.h>
  1861. //计算字符串长度的函数
  1862. int str_len(const char *string)
  1863. {
  1864. //char *temp=string; 编译报错!
  1865. //*string='x'; 编译报错!
  1866. int i=0;
  1867. while (*(string+i)!=NULL)
  1868. i++;
  1869. return i;
  1870. }
  1871. //main()函数中测试str_len()
  1872. void main()
  1873. {
  1874. char a[]="ABCDE";
  1875. cout<<a<<"\t"<<str_len(a)<<endl;
  1876. char *str="Hello!";
  1877. cout<<str<<"\t"<<str_len(str)<<endl;
  1878. cout<<"This is a test."<<"\t"<<str_len("This is a test.")<<endl;
  1879. }
  1880. #include<iostream.h>
  1881. void disp(void); //这个函数声明语句不能少
  1882. //定义main()函数的参数和返回值类型是void类型
  1883. void main(void)
  1884. {
  1885. //调用void类型函数
  1886. disp();
  1887. }
  1888. //以下定义disp()函数
  1889. void disp(void) {
  1890. cout<<" You are welcome."<<endl;
  1891. }
  1892. #include<iostream.h>
  1893. //函数原型语句
  1894. int abs(int x);
  1895. long abs(long x);
  1896. float abs(float x);
  1897. //main()函数的定义
  1898. void main(void)
  1899. {
  1900. //声明变量
  1901. int i1=32767,i2=-32767;
  1902. long l1=456789,l2=-456789;
  1903. float x1=1.1234,x2=-1.1234;
  1904. //直接在cout输出中调用函数
  1905. cout<<abs(i1)<<","<<abs(i2)<<endl;
  1906. cout<<abs(l1)<<","<<abs(l2)<<endl;
  1907. cout<<abs(x1)<<","<<abs(x2)<<endl;
  1908. }
  1909. //定义int型的abs()函数
  1910. int abs(int x) {
  1911. if (x<0)
  1912. return(-x);
  1913. else
  1914. return(x);
  1915. }
  1916. //定义long型的abs()函数
  1917. long abs(long x) {
  1918. if (x<0)
  1919. return(-x);
  1920. else
  1921. return(x);
  1922. }
  1923. //定义float型 abs函数
  1924. float abs(float x) {
  1925. if (x<0.0)
  1926. return(-x);
  1927. else
  1928. return(x);
  1929. }
  1930. #include<iostream.h>
  1931. //max()为内联函数
  1932. inline int max(int x,int y) //注意inline关键字
  1933. {
  1934. return x>y?x:y;
  1935. }
  1936. //定义main()函数
  1937. main()
  1938. {
  1939. int a=3,b=5,c;
  1940. c=max(a,b);
  1941. cout<<"max("<<a<<","<<b<<")="<<c<<endl;
  1942. cout<<"max("<<15<<","<<11<<")="<<max(15,11)<<endl;
  1943. }
  1944. #include<iostream.h>
  1945. main()
  1946. {
  1947. //函数原型声明
  1948. int fact(int x);
  1949. int n,sn;
  1950. //依次从键盘上输入3个正整型数据计算它们的阶乘
  1951. for (int i=1;i<=3;i++)
  1952. {
  1953. cout<<i<<" n=";
  1954. cin>>n;
  1955. sn=fact(n);
  1956. cout<<n<<"!="<<sn<<endl;
  1957. }
  1958. }
  1959. //以下是采用递归方法定义的fact()函数
  1960. int fact(int x)
  1961. {
  1962. if (x==0) return(1);
  1963. return(x*fact(x-1)); //此处又调用了它自身
  1964. }
  1965. #include<iostream.h>
  1966. //带参数的main()函数
  1967. int main(int argc,char *argv[])
  1968. {
  1969. int i;
  1970. for(i=0;i<argc;i++)
  1971. cout<<i<<":"<<argv[i]<<endl;
  1972. return 0;
  1973. }
  1974. #include<iostream.h>
  1975. //用函数原型声明要使用的函数
  1976. void show_array1(int*,int);
  1977. void show_array2(int a[],int);
  1978. void sort(int*,int);
  1979. main()
  1980. {
  1981. //声明数组并初始化
  1982. int a[]={2,4,6,1,3,5};
  1983. int b[3][3]={{2,4,6},{1,3,5},{0,1,2}};
  1984. //显示数组的值
  1985. cout<<"show_array1(int*,int):"<<endl;
  1986. show_array1(a,6);
  1987. show_array1(&b[0][0],3*3);
  1988. //用sort1排序并显示
  1989. cout<<"sort(int*,int) and show_array1(int*,int): "<<endl;
  1990. sort(a,6);
  1991. show_array1(a,6);
  1992. sort(&b[0][0],3*3);
  1993. show_array1(&b[0][0],9);
  1994. //显示数组的值
  1995. cout<<"show_array2(int a[],int):"<<endl;
  1996. show_array2(a,6);
  1997. show_array2(&b[0][0],3*3);
  1998. }
  1999. //显示数组,用指针当参数
  2000. void show_array1(int *p,int size) {
  2001. for(int i=0;i<size;i++)
  2002. cout<<*(p+i)<<" ";
  2003. cout<<endl;
  2004. }
  2005. //显示数组,用数组当参数
  2006. void show_array2(int a[],int size) {
  2007. for(int i=0;i<size;i++)
  2008. cout<<a[i]<<" ";
  2009. cout<<endl;
  2010. }
  2011. //对数组按从大到小顺序排序
  2012. void sort(int *p,int size) {
  2013. int t;
  2014. for (int i=0;i<size-1;i++)
  2015. for (int j=i+1;j<size;j++)
  2016. if (*(p+i)<=*(p+j))
  2017. {
  2018. t=*(p+i);
  2019. *(p+i)=*(p+j);
  2020. *(p+j)=t;
  2021. }
  2022. }
  2023. #include<iostream.h>
  2024. //定义结构
  2025. struct student {
  2026. char name[10];
  2027. float grade;
  2028. };
  2029. //更改student数据的grade成员,参数形式为引用
  2030. void change(student &x,float grade)
  2031. {
  2032. x.grade=grade;
  2033. }
  2034. //更改student数据的grade成员,参数形式为指针
  2035. void change1(student *p,float grade)
  2036. {
  2037. p->grade=grade;
  2038. }
  2039. //更改student类型的数据,普通参数形式
  2040. void change2(student x,float grade)
  2041. {
  2042. x.grade=grade;
  2043. }
  2044. //显示student类型的数据,参数形式为引用
  2045. void show(student &x)
  2046. {
  2047. cout<<x.name<<" "<<x.grade<<endl;
  2048. }
  2049. //在main()函数中,测试对结构的处理函数
  2050. void main()
  2051. {
  2052. student a={"ZhangHua",351.5};
  2053. //显示a的数据
  2054. show(a);
  2055. //用change修改分数,并显示
  2056. cout<<"change(student &x,float grade):"<<endl;
  2057. change(a,360);
  2058. show(a);
  2059. //用change1修改分数,并显示
  2060. cout<<"change1(student *p,float grade):"<<endl;
  2061. change1(&a,375);
  2062. show(a);
  2063. //用change2修改分数,并显示
  2064. cout<<"change2(student x,float grade):"<<endl;
  2065. change2(a,380.5);
  2066. show(a);
  2067. }
  2068. #include<iostream.h>
  2069. //定义函数计算数组的和和平均值
  2070. void calculate(int a[],int size,int& sum,float& average)
  2071. {
  2072. sum=0;
  2073. for (int i=0;i<size;i++) {
  2074. sum+=a[i];
  2075. }
  2076. average=sum/size;
  2077. }
  2078. //定义显示数组的函数
  2079. void put_arr(int a[],int size)
  2080. {
  2081. for(int i=0;i<size;i++)
  2082. cout<<a[i]<<" ";
  2083. cout<<endl;
  2084. }
  2085. main()
  2086. {
  2087. //声明数组并初始化
  2088. int asize,bsize;
  2089. int a[]={2,4,6,1,3,5};
  2090. int b[]={1,3,5,7,9,11,13,15};
  2091. //显示数组的值
  2092. asize=sizeof(a)/sizeof(int);
  2093. cout<<"put_arr(a,asize):"<<endl;
  2094. put_arr(a,asize);
  2095. bsize=sizeof(b)/sizeof(int);
  2096. cout<<"put_arr(b,bsize):"<<endl;
  2097. put_arr(b,bsize);
  2098. //计算数组的和和平均值
  2099. float a_ave,b_ave;
  2100. int a_sum,b_sum;
  2101. cout<<"calculate(a,asize,a_sum,a_ave):"<<endl;
  2102. calculate(a,asize,a_sum,a_ave);
  2103. cout<<"a_sum="<<a_sum;
  2104. cout<<" a_ave="<<a_ave<<endl;
  2105. cout<<"calculate(b,bsize,b_sum,b_ave):"<<endl;
  2106. calculate(b,bsize,b_sum,b_ave);
  2107. cout<<"b_sum="<<b_sum;
  2108. cout<<" b_ave="<<b_ave<<endl;
  2109. }
  2110. #include<iostream.h>
  2111. //参数为函数指针的函数
  2112. int get_result(int a, int b, int (*sub)(int,int))
  2113. {
  2114. int r;
  2115. r=sub(a,b);
  2116. return r;
  2117. }
  2118. //计算最大值
  2119. int max(int a, int b)
  2120. {
  2121. cout<<"In max"<<endl;
  2122. return((a > b) ? a: b);
  2123. }
  2124. //计算最小值
  2125. int min(int a, int b)
  2126. {
  2127. cout<<"In min"<<endl;
  2128. return((a < b) ? a: b);
  2129. }
  2130. //求和
  2131. int sum(int a, int b)
  2132. {
  2133. cout<<"In sum"<<endl;
  2134. return(a+b);
  2135. }
  2136. //测试指向函数的指针
  2137. void main(void)
  2138. {
  2139. int a,b,result;
  2140. //测试3次
  2141. for (int i=1;i<=3;i++) {
  2142. cout<<"Input a and b :";
  2143. cin>>a>>b;
  2144. cout<<i<<"\tget_result("<<a<<","<<b<<", &max):"<<endl;
  2145. result =get_result(a, b, &max);
  2146. cout<<"Max of "<<a<<" and "<<b<<" is "<<result<<endl;
  2147. result = get_result(a, b, &min);
  2148. cout<<"Min of "<<a<<" and "<<b<<" is "<<result<<endl;
  2149. result = get_result(a, b, &sum);
  2150. cout<<"Sum of "<<a<<" and "<<b<<" is "<<result<<endl;
  2151. }
  2152. }
  2153. #include<iostream.h>
  2154. #include<stdio.h>
  2155. #define size 3
  2156. //定义book结构类型
  2157. struct book
  2158. {
  2159. char title[20];
  2160. char author[15];
  2161. int pages;
  2162. float price;
  2163. };
  2164. //book结构的输入函数
  2165. input_book(book& bk,char *name)
  2166. {
  2167. cout<<name<<":"<<endl;
  2168. cout<<"title:";
  2169. cin>>bk.title;
  2170. cout<<"author:";
  2171. cin>>bk.author;
  2172. cout<<"pages:";
  2173. cin>>bk.pages;
  2174. cout<<"price:";
  2175. cin>>bk.price;
  2176. }
  2177. //book结构的输出函数
  2178. output_book(book& bk,char *name)
  2179. {
  2180. cout<<name<<": ";
  2181. cout<<bk.title<<" ";
  2182. cout<<bk.author<<" ";
  2183. cout<<bk.pages<<" ";
  2184. cout<<bk.price<<endl;
  2185. }
  2186. void main(void)
  2187. {
  2188. //声明变量和结构数组
  2189. int i;
  2190. char str[20];
  2191. book bk[size];
  2192. //输入结构数组
  2193. for(i=0;i<size;i++) {
  2194. sprintf(str,"bk[%d]",i+1);
  2195. input_book(bk[i],str);
  2196. }
  2197. //显示结构数组
  2198. for(i=0;i<size;i++) {
  2199. sprintf(str,"bk[%d]",i+1);
  2200. output_book(bk[i],str);
  2201. }
  2202. }
  2203. #include<iostream.h>
  2204. //声明全局变量并初始化
  2205. extern int a[]={1,2,3};
  2206. extern float p=3.14;
  2207. //在show()函数中使用外部变量
  2208. show() {
  2209. int i;
  2210. cout<<"In show():"<<endl;
  2211. cout<<"p="<<p<<endl;
  2212. cout<<"a[]: ";
  2213. for (i=0;i<=2;i++)
  2214. cout<<a[i]<<" ";
  2215. cout<<endl;
  2216. //cout<<"y="<<y<<endl; 编译出错!
  2217. }
  2218. //声明外部变量并初始化
  2219. int y=5678;
  2220. //在main()函数中使用外部变量
  2221. main()
  2222. {
  2223. //声明局部变量
  2224. int i,p=100;
  2225. //显示重名变量
  2226. cout<<"In main():"<<endl;
  2227. cout<<"p="<<p<<endl;
  2228. //显示全局变量
  2229. cout<<"::p="<<::p<<endl;
  2230. cout<<"a[]: ";
  2231. for (i=0;i<=2;i++)
  2232. cout<<a[i]<<" ";
  2233. cout<<endl;
  2234. cout<<"y="<<y<<endl; //编译正确!
  2235. show(); //调用函数
  2236. }
  2237. #include <iostream.h>
  2238. //使用静态变量的计数器函数
  2239. count1()
  2240. {
  2241. //声明静态变量i,并置初值为0。i在count()中局部可见
  2242. static int i=0;
  2243. return(++i);
  2244. }
  2245. //使用局部变量的计数器函数
  2246. count2()
  2247. {
  2248. int i=0;
  2249. return(++i);
  2250. }
  2251. //在main()函数中调用count()函数
  2252. main()
  2253. {
  2254. int i;
  2255. //调用count1()10次
  2256. cout<<"count1():"<<endl;
  2257. for (i=1;i<=12;i++)
  2258. cout<<count1()<<" ";
  2259. cout<<endl;
  2260. //调用count2()10次
  2261. cout<<"count2():"<<endl;
  2262. for (i=1;i<=12;i++)
  2263. cout<<count2()<<" ";
  2264. cout<<endl;
  2265. }
  2266. // p1-851.cpp 为main()函数文件
  2267. #include<iostream.h>
  2268. main()
  2269. {
  2270. int i,s=0;
  2271. extern int fact(int x);
  2272. for (i=2;i<=6;i=i+2)
  2273. s+=fact(i);
  2274. cout<<"s="<<s<<endl;
  2275. }
  2276. // p1-852.cpp为计算阶乘函数文件
  2277. //定义fact()函数为外部(extern)函数
  2278. extern int fact(int x)
  2279. {
  2280. int i,t=1;
  2281. if(x==0) return(1);
  2282. for(i=1;i<=x;i++)
  2283. t*=i;
  2284. return(t);
  2285. }
  2286. #include<iostream.h>
  2287. #include<stdio.h>
  2288. #include<string.h>
  2289. #include<process.h>
  2290. main() {
  2291. //声明变量
  2292. FILE *fp1;
  2293. char str[80];
  2294. //从键盘上任意输入一个字符串
  2295. cout<<"Inupt a string:";
  2296. cin.getline(str,80);
  2297. //以写入方式打开d.dat文件
  2298. if ((fp1=fopen("d.dat","w"))==NULL)
  2299. {
  2300. cout<<"\nCould not open the file."<<endl;
  2301. cout<<"Exiting program."<<endl;
  2302. exit(1); //结束程序执行
  2303. }
  2304. // 写"流"文件
  2305. fputs(str,fp1);
  2306. fputs("\n",fp1);
  2307. fclose(fp1); //关闭文件
  2308. // 以读方式打开d.dat文件
  2309. if ((fp1=fopen("d.dat","r"))==NULL)
  2310. {
  2311. cout<<"\nCould not open the file."<<endl;
  2312. cout<<"Exiting program."<<endl;
  2313. exit(1); //结束程序执行
  2314. }
  2315. // 循环从"流"文件读取字符,并显示
  2316. char ch;
  2317. while ((ch=fgetc(fp1))!=EOF)
  2318. cout<<ch;
  2319. cout<<endl;
  2320. fclose(fp1); //关闭文件
  2321. }
  2322. #include<iostream.h>
  2323. #include <process.h>
  2324. #include<stdio.h>
  2325. #include<conio.h>
  2326. void main(void) {
  2327. //变量声明
  2328. char ch;
  2329. FILE *fp1;
  2330. //以写入方式打开d.dat文件
  2331. if ((fp1=fopen("d.dat","w"))==NULL) {
  2332. cout<<"\nCould not open the file."<<endl;
  2333. cout<<"Exiting program."<<endl;
  2334. exit(1); //结束程序执行
  2335. }
  2336. //循环从键盘上读取字符,写入"流"文件
  2337. cout<<"char:"<<endl;
  2338. cin>>ch;
  2339. while (ch!='*') {
  2340. fputc(ch,fp1); //将字符写到fp1指向的"流"文件中
  2341. cin>>ch;
  2342. }
  2343. fclose(fp1); //关闭文件
  2344. // 以读方式打开d.dat文件
  2345. if ((fp1=fopen("d.dat","r"))==NULL)
  2346. {
  2347. cout<<"\nCould not open the file."<<endl;
  2348. cout<<"Exiting program."<<endl;
  2349. exit(1); //结束程序执行
  2350. }
  2351. // 循环从"流"文件读取字符,并显示
  2352. while ((ch=fgetc(fp1))!=EOF)
  2353. cout<<ch<<" ";
  2354. cout<<endl;
  2355. fclose(fp1); //关闭文件
  2356. }
  2357. #include<iostream.h>
  2358. #include<stdio.h>
  2359. #include<string.h>
  2360. #include<process.h>
  2361. main() {
  2362. //声明变量
  2363. int i=0;
  2364. char p[100]; // 声明输入缓冲区
  2365. FILE *fp1; // 声明文件指针变量
  2366. //以写入方式打开d.dat文件
  2367. if ((fp1=fopen("d.dat","w"))==NULL)
  2368. {
  2369. cout<<"\nCould not open the file."<<endl;
  2370. cout<<"Exiting program."<<endl;
  2371. exit(1); //结束程序执行
  2372. }
  2373. // 写文件操作
  2374. for (i=1;;i++) { //无条件循环
  2375. cout<<i<<" string:";
  2376. cin>>p; //从键盘上输入数据
  2377. if (stricmp(p,"end")) { //如果输入的字符串为end,则结束循环
  2378. fputs(p,fp1); //写入文件操作
  2379. fputs("\n",fp1);
  2380. }
  2381. else
  2382. break; //退出循环
  2383. }
  2384. fclose(fp1); //关闭文件
  2385. // 以读方式打开d.dat文件
  2386. if ((fp1=fopen("d.dat","r"))==NULL)
  2387. {
  2388. cout<<"\nCould not open the file."<<endl;
  2389. cout<<"Exiting program."<<endl;
  2390. exit(1); //结束程序执行
  2391. }
  2392. // 循环从文件读取字符,并显示
  2393. while (fgets(p,100,fp1)!=NULL)
  2394. cout<<p;
  2395. fclose(fp1); //关闭文件
  2396. }
  2397. #include<iostream.h>
  2398. #include<stdio.h>
  2399. #include<string.h>
  2400. #include<process.h>
  2401. #include<stdlib.h>
  2402. #define MAX 10
  2403. main() {
  2404. //声明变量
  2405. int i,n;
  2406. FILE *fp1; // 声明文件指针变量
  2407. //以写入方式打开d.dat文件
  2408. if ((fp1=fopen("d.dat","w"))==NULL)
  2409. {
  2410. cout<<"\nCould not open the file."<<endl;
  2411. cout<<"Exiting program."<<endl;
  2412. exit(1); //结束程序执行
  2413. }
  2414. // 写文件操作
  2415. for (i=1;i<=MAX;i++) {
  2416. n=rand(); //产生1个整数随机数
  2417. putw(n,fp1);
  2418. cout<<n<<" ";
  2419. }
  2420. cout<<endl<<"--------------------"<<endl;
  2421. fclose(fp1); //关闭文件
  2422. // 以读方式打开d.dat文件
  2423. if ((fp1=fopen("d.dat","r"))==NULL)
  2424. {
  2425. cout<<"\nCould not open the file."<<endl;
  2426. cout<<"Exiting program."<<endl;
  2427. exit(1); //结束程序执行
  2428. }
  2429. // 循环从"流"文件读取字符,并显示
  2430. while ((n=getw(fp1))!=EOF)
  2431. cout<<n<<" ";
  2432. fclose(fp1); //关闭文件
  2433. }
  2434. #include<iostream.h>
  2435. #include<stdio.h>
  2436. #include<string.h>
  2437. #include<process.h>
  2438. #include<stdlib.h>
  2439. #define MAX 3
  2440. main() {
  2441. //定义结构类型
  2442. struct student {
  2443. int num;
  2444. char name[10];
  2445. float grade;
  2446. };
  2447. //声明数组和变量
  2448. student st[3];
  2449. int i;
  2450. FILE *fp1; // 声明文件指针变量
  2451. //以写入方式打开d.dat文件
  2452. if ((fp1=fopen("d.dat","w"))==NULL)
  2453. {
  2454. cout<<"\nCould not open the file."<<endl;
  2455. cout<<"Exiting program."<<endl;
  2456. exit(1); //结束程序执行
  2457. }
  2458. //从键盘上读数据,写入文件
  2459. cout<<" num name grade"<<endl;
  2460. for (i=0;i<MAX;i++) {
  2461. cout<<i+1<<" ";
  2462. cin>>st[i].num;
  2463. cin>>st[i].name;
  2464. cin>>st[i].grade;
  2465. fprintf(fp1,"%d %s %f\n",st[i].num,st[i].name,st[i].grade);
  2466. }
  2467. fclose(fp1); //关闭文件
  2468. // 以读方式打开d.dat文件
  2469. if ((fp1=fopen("d.dat","r"))==NULL)
  2470. {
  2471. cout<<"\nCould not open the file."<<endl;
  2472. cout<<"Exiting program."<<endl;
  2473. exit(1); //结束程序执行
  2474. }
  2475. // 循环从"流"文件读取字符,并显示
  2476. student t;
  2477. while ((fscanf(fp1, "%d %s %f",&t.num,t.name,&t.grade))!=EOF) {
  2478. cout<<t.num<<" ";
  2479. cout<<t.name<<" ";
  2480. cout<<t.grade<<endl;
  2481. }
  2482. fclose(fp1); //关闭文件
  2483. }
  2484. #include<iostream.h>
  2485. #include <process.h>
  2486. #include <stdlib.h>
  2487. #include <stdio.h>
  2488. int main(void)
  2489. {
  2490. FILE *fpd,*fpw; // 声明FILE结构指针变量
  2491. unsigned char dw;
  2492. int i=0;
  2493. //以二进制读方式打开Calc.exe文件
  2494. if((fpd=fopen("C:\WINDOWS\Calc.exe", "rb"))==NULL)
  2495. {
  2496. cout<<"\nCould not open the file."<<endl;
  2497. cout<<"Exiting program."<<endl;
  2498. exit(1); //结束程序执行
  2499. }
  2500. // 以二进制写方式打开test.exe文件
  2501. if((fpw=fopen("test.exe", "wb+"))==NULL)
  2502. {
  2503. cout<<"\nCould not open the file."<<endl;
  2504. cout<<"Exiting program."<<endl;
  2505. exit(1); //结束程序执行
  2506. }
  2507. // 二进制文件读写操作,每次指定读写1个字节
  2508. while(!feof(fpd)) { //使用feof()判断文件尾
  2509. fread(&dw, 1, 1, fpd);
  2510. fwrite(&dw, 1, 1, fpw);
  2511. }
  2512. // 关闭文件
  2513. fclose(fpd);
  2514. fclose(fpw);
  2515. //执行Calc.exe和Calc.exe文件
  2516. cout<<"1 Run C:\WINDOWS\Calc.exe"<<endl;
  2517. system("C:\WINDOWS\Calc.exe");
  2518. cout<<"-------------------"<<endl;
  2519. cout<<"2 Run test.exe!"<<endl;
  2520. system("test.exe");
  2521. }
  2522. #include<iostream.h>
  2523. #include <process.h>
  2524. #include<stdio.h>
  2525. #include<conio.h>
  2526. void main(void) {
  2527. //声明变量
  2528. int i;
  2529. char ch;
  2530. FILE *fp1;
  2531. //以写入方式打开d.dat文件
  2532. if ((fp1=fopen("d.dat","w"))==NULL) {
  2533. cout<<"\nCould not open the file."<<endl;
  2534. cout<<"Exiting program."<<endl;
  2535. exit(1); //结束程序执行
  2536. }
  2537. //循环从键盘上读取字符,写入文件
  2538. cout<<"char:";
  2539. cin>>ch;
  2540. while (ch!='*') {
  2541. fputc(ch,fp1); //将字符写到fp1指向的"流"文件中
  2542. cin>>ch;
  2543. }
  2544. cout<<"--------------------"<<endl;
  2545. fclose(fp1); //关闭文件
  2546. //以读方式打开d.dat文件
  2547. if ((fp1=fopen("d.dat","r"))==NULL)
  2548. {
  2549. cout<<"\nCould not open the file."<<endl;
  2550. cout<<"Exiting program."<<endl;
  2551. exit(1); //结束程序执行
  2552. }
  2553. //循环从文件读取字符,并显示
  2554. while ((ch=fgetc(fp1))!=EOF)
  2555. cout<<ch;
  2556. cout<<endl<<"--------------------"<<endl;
  2557. //以下按倒序方式读取文件中的字符,并显示
  2558. for (i=-1;;i--) {
  2559. fseek(fp1,i,2); //设置文件指针,偏移量为i,相对文件尾
  2560. if ((ch=fgetc(fp1))!=EOF)
  2561. cout<<ch;
  2562. else
  2563. break;
  2564. }
  2565. cout<<endl<<"--------------------"<<endl;
  2566. //以下读取"流"文件中偶数位置上的字符,并打印
  2567. long position;
  2568. for (i=0;;i=i+2) {
  2569. fseek(fp1,i,0); //设置文件指针,偏移量为i,相对文件头
  2570. position=ftell(fp1);
  2571. if ((ch=fgetc(fp1))==EOF) //遇到文件尾,则退出,否则打印读取的字符
  2572. break;
  2573. else {
  2574. cout<<position<<" :"<<ch<<endl;
  2575. }
  2576. }
  2577. cout<<endl;
  2578. fclose(fp1); //关闭文件
  2579. }
  2580. #include<iostream.h>
  2581. #include<stdio.h>
  2582. #include<process.h>
  2583. #include<stdlib.h>
  2584. #define MAX 5
  2585. //显示数组的数据
  2586. void show_array(double x[],int size) {
  2587. for(int i=0;i<size;i++)
  2588. cout<<x[i]<<" ";
  2589. cout<<endl;
  2590. }
  2591. //main函数测试数组数据的文件读写
  2592. int main(void)
  2593. {
  2594. //声明变量
  2595. FILE *fp; // 声明FILE结构指针变量
  2596. int i;
  2597. double a[MAX]={1.0,1.2,1.4,1.6,1.8};
  2598. //显示数组a的数据
  2599. cout<<"a:";
  2600. show_array(a,MAX);
  2601. //打开d.dat文件
  2602. if ((fp=fopen("d.dat","wb+"))==NULL)
  2603. {
  2604. cout<<"\nCould not open the file."<<endl;
  2605. cout<<"Exiting program."<<endl;
  2606. exit(1); //结束程序执行
  2607. }
  2608. //以单个元素对数组进行文件读操作
  2609. for(i=0;i<MAX;i++) {
  2610. fwrite(&a[i], sizeof(double), 1, fp);
  2611. }
  2612. rewind(fp); //恢复读写指针的位置
  2613. //以单个元素对数组进行文件读操作
  2614. double b[MAX];
  2615. for(i=0;i<MAX;i++) {
  2616. if (!feof(fp)) //使用feof()判断文件尾
  2617. fread(&b[i], sizeof(double), 1, fp);
  2618. else
  2619. break;
  2620. }
  2621. cout<<"b:";
  2622. show_array(b,MAX);//显示数组b的数据
  2623. fclose(fp); // 关闭文件
  2624. //打开d1.dat文件
  2625. if ((fp=fopen("d1.dat","wb+"))==NULL)
  2626. {
  2627. cout<<"\nCould not open the file."<<endl;
  2628. cout<<"Exiting program."<<endl;
  2629. exit(1); //结束程序执行
  2630. }
  2631. //将数组当成数据块写入文件
  2632. fwrite(&a, sizeof(double), MAX, fp);
  2633. rewind(fp); //恢复读写指针的位置
  2634. //将数组当成数据块从文件中读取
  2635. double c[MAX];
  2636. if (!feof(fp)) //使用feof()判断文件尾
  2637. fread(&c, sizeof(double),MAX,fp);
  2638. cout<<"c:";
  2639. show_array(c,MAX); //显示数组c的数据
  2640. fclose(fp); // 关闭文件
  2641. }
  2642. #include<iostream.h>
  2643. #include<stdio.h>
  2644. #include<process.h>
  2645. #include<stdlib.h>
  2646. #define MAX 5
  2647. //定义结构类型
  2648. struct student {
  2649. int num;
  2650. char name[20];
  2651. float grade;
  2652. };
  2653. //显示student结构数据
  2654. void show_str(student a,char *name) {
  2655. cout<<name<<":"<<endl;
  2656. cout<<a.num<<" "<<a.name<<" "<<a.grade;
  2657. cout<<endl;
  2658. }
  2659. //main函数测试结构数据的文件读写
  2660. int main(void)
  2661. {
  2662. //声明变量
  2663. FILE *fp;
  2664. //声明FILE结构指针变量
  2665. student st={1001,"ZhangBin",85.5};
  2666. //显示st结构数据
  2667. show_str(st,"st");
  2668. //打开d.dat文件
  2669. if ((fp=fopen("d.dat","wb+"))==NULL)
  2670. {
  2671. cout<<"\nCould not open the file."<<endl;
  2672. cout<<"Exiting program."<<endl;
  2673. exit(1); //结束程序执行
  2674. }
  2675. //用fprintf()函数写结构数据到文件
  2676. fprintf(fp,"%d %s %f",st.num,st.name,st.grade);
  2677. rewind(fp); //恢复读写指针的位置
  2678. //用fscanf()函数读文件中的数据赋值给结构并显示
  2679. student temp;
  2680. fscanf(fp, "%d %s %f",&temp.num,temp.name,&temp.grade);
  2681. show_str(temp,"temp");
  2682. cout<<"-----------------------"<<endl;
  2683. fclose(fp); // 关闭文件
  2684. //将结构数据当成数据块进行读写
  2685. if ((fp=fopen("d1.dat","wb+"))==NULL) //打开d1.dat文件
  2686. {
  2687. cout<<"\nCould not open the file."<<endl;
  2688. cout<<"Exiting program."<<endl;
  2689. exit(1); //结束程序执行
  2690. }
  2691. //声明结构数组并初始化
  2692. int i;
  2693. student starr[3]={{101,"WangPing",92},{102,"Li",85},{103,"LiuMin",97}};
  2694. //显示结构数组
  2695. for(i=0;i<3;i++)
  2696. show_str(starr[i],"starr");
  2697. //将结构数组当成数据块写入文件
  2698. fwrite(starr, sizeof(student), 3, fp);
  2699. rewind(fp); //恢复读写指针的位置
  2700. //按数据块从文件中读取数据赋值给结构数组
  2701. student temp_arr[3];
  2702. if (!feof(fp)) //使用feof()判断文件尾
  2703. fread(temp_arr, sizeof(student),3,fp);
  2704. for(i=0;i<3;i++)
  2705. show_str(temp_arr[i],"temp_arr");
  2706. fclose(fp); // 关闭文件
  2707. }
  2708. #include<stdio.h>
  2709. #include<stdlib.h>
  2710. #include<iostream.h>
  2711. int main(void)
  2712. {
  2713. //声明变量
  2714. char ch;
  2715. char str[20];
  2716. int n;
  2717. float x;
  2718. //用stdin从键盘上输入数据
  2719. fprintf(stdout,"ch str\n");
  2720. fscanf(stdin,"%c %s",&ch,str);
  2721. fprintf(stdout,"n x \n");
  2722. fscanf(stdin,"%d %f",&n,&x);
  2723. cout<<"----------------"<<endl;
  2724. //输出显示
  2725. fprintf(stdout,"ch=%c str=%s",ch,str);
  2726. fprintf(stdout,"\nn=%d x=%f",n,x);
  2727. cout<<endl;
  2728. }
  2729. #include <stdio.h>
  2730. void main( void )
  2731. {
  2732. int c;
  2733. /* Create an error by writing to standard input. */
  2734. putc( 'A', stdin );
  2735. if( ferror( stdin ) )
  2736. {
  2737. perror( "Write error" );
  2738. clearerr( stdin );
  2739. }
  2740. /* See if read causes an error. */
  2741. printf( "Will input cause an error? " );
  2742. c = getc( stdin );
  2743. if( ferror( stdin ) )
  2744. {
  2745. perror( "Read error" );
  2746. clearerr( stdin );
  2747. }
  2748. }
  2749. #include<iostream.h>
  2750. #include<math.h> //此预处理指令不可少
  2751. const double HD=3.1415926/180;
  2752. main() {
  2753. cout<<"x\tsin(x)"<<endl;
  2754. for (int i=0;i<=180;i=i+30)
  2755. cout<<i<<"\t"<<sin(i*HD)<<endl;
  2756. }
  2757. #include<iostream.h>
  2758. //以下是几个简单宏替换预处理指令
  2759. #define YES 1
  2760. #define PI 3.1415926
  2761. #define RAD PI/180
  2762. #define MESG "This is a string."
  2763. //以下是主程序
  2764. main() {
  2765. //以下各语句使用了宏替换
  2766. cout<<"YES="<<YES<<endl;
  2767. if (YES)
  2768. cout<<"PI="<<PI<<endl;
  2769. cout<<"RAD="<<RAD<<endl;
  2770. cout<<MESG<<endl;
  2771. }
  2772. #include<iostream.h>
  2773. //以下为带参数宏替换的预处理指令
  2774. #define PRINT(k) cout<<(k)<<endl;
  2775. #define MAX(a,b) ((a)>(b) ? (a):(b))
  2776. main()
  2777. {
  2778. int i=3,j=2;
  2779. //MAX(a,b)宏替换的使用
  2780. cout<<"MAX(10,12)="<<MAX(10,12)<<endl;
  2781. cout<<"MAX(i,j)="<<MAX(i,j)<<endl;
  2782. cout<<"MAX(2*i,j+3)="<<MAX(2*i,j+3)<<endl;
  2783. //PRINT(k)宏替换的使用
  2784. PRINT(5);
  2785. PRINT(MAX(7,i*j));
  2786. }
  2787. #include<iostream.h>
  2788. #define PI 3.1416
  2789. main() {
  2790. int i=100;
  2791. #if 1
  2792. cout<<"i="<<i<<endl;
  2793. #endif
  2794. #ifdef PI
  2795. cout<<"1 PI="<<PI<<endl;
  2796. #endif
  2797. #ifndef PI
  2798. cout<<"2 PI="<<PI<<endl; //此语句不被编译执行
  2799. #endif
  2800. }
  2801. #include<iostream.h>
  2802. const int MAX=5; //假定栈中最多保存5个数据
  2803. //定义名为stack的类,其具有栈功能
  2804. class stack {
  2805. //数据成员
  2806. float num[MAX]; //存放栈数据的数组
  2807. int top; //指示栈顶位置的变量
  2808. public:
  2809. //成员函数
  2810. void init(void) { top=0; } //初始化函数
  2811. void push(float x) //入栈函数
  2812. {
  2813. if (top==MAX){
  2814. cout<<"Stack is full !"<<endl;
  2815. return;
  2816. };
  2817. num[top]=x;
  2818. top++;
  2819. }
  2820. float pop(void) //出栈函数
  2821. {
  2822. top--;
  2823. if (top<0){
  2824. cout<<"Stack is underflow !"<<endl;
  2825. return 0;
  2826. };
  2827. return num[top];
  2828. }
  2829. }
  2830. //以下是main()函数,其用stack类创建栈对象,并使用了这些对象
  2831. main(void)
  2832. {
  2833. //声明变量和对象
  2834. int i;
  2835. float x;
  2836. stack a,b; //声明(创建)栈对象
  2837. //以下对栈对象初始化
  2838. a.init();
  2839. b.init();
  2840. //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈对象
  2841. for (i=1; i<=MAX; i++)
  2842. a.push(2*i);
  2843. //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示
  2844. for (i=1; i<=MAX; i++)
  2845. cout<<a.pop()<<" ";
  2846. cout<<endl;
  2847. //以下利用循环和push()成员函数将键盘输入的数据依次入b栈
  2848. cout<<"Please input five numbers."<<endl;
  2849. for (i=1; i<=MAX; i++) {
  2850. cin>>x;
  2851. b.push(x);
  2852. }
  2853. //以下利用循环和pop()成员函数依次弹出b栈中的数据并显示
  2854. for (i=1; i<=MAX; i++)
  2855. cout<<b.pop()<<" ";
  2856. }
  2857. #include<iostream.h>
  2858. const int MAX=5; //假定栈中最多保存5个数据
  2859. //定义名为stack的具有栈功能的类
  2860. class stack {
  2861. //数据成员
  2862. float num[MAX]; //存放栈数据的数组
  2863. int top; //指示栈顶位置的变量
  2864. public:
  2865. //成员函数
  2866. stack(void) //初始化函数
  2867. {
  2868. top=0;
  2869. cout<<"Stack initialized."<<endl;
  2870. }
  2871. void push(float x) //入栈函数
  2872. {
  2873. if (top==MAX){
  2874. cout<<"Stack is full !"<<endl;
  2875. return;
  2876. };
  2877. num[top]=x;
  2878. top++;
  2879. }
  2880. float pop(void) //出栈函数
  2881. {
  2882. top--;
  2883. if (top<0){
  2884. cout<<"Stack is underflow !"<<endl;
  2885. return 0;
  2886. };
  2887. return num[top];
  2888. }
  2889. }
  2890. //以下是main()函数,其用stack类创建栈对象,并使用了这些对象
  2891. main(void)
  2892. {
  2893. //声明变量和对象
  2894. int i;
  2895. float x;
  2896. stack a,b; //声明(创建)栈对象并初始化
  2897. //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈
  2898. for (i=1; i<=MAX; i++)
  2899. a.push(2.0*i);
  2900. //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示
  2901. for (i=1; i<=MAX; i++)
  2902. cout<<a.pop()<<" ";
  2903. cout<<endl;
  2904. //以下利用循环和push()成员函数将键盘输入的数据依次入b栈
  2905. cout<<"Please input five numbers."<<endl;
  2906. for (i=1; i<=MAX; i++) {
  2907. cin>>x;
  2908. b.push(x);
  2909. }
  2910. //以下利用循环和pop()成员函数依次弹出b栈中的数据并显示
  2911. for (i=1; i<=MAX; i++)
  2912. cout<<b.pop()<<" ";
  2913. cout<<endl;
  2914. }
  2915. #include<iostream.h>
  2916. const int MAX=5; //假定栈中最多保存5个数据
  2917. //定义名为stack的具有栈功能的类
  2918. class stack {
  2919. //数据成员
  2920. float num[MAX]; //存放栈数据的数组
  2921. int top; //指示栈顶位置的变量
  2922. public:
  2923. //成员函数
  2924. stack(char c) //初始化函数
  2925. {
  2926. top=0;
  2927. cout<<"Stack "<<c<<" initialized."<<endl;
  2928. }
  2929. void push(float x) //入栈函数
  2930. {
  2931. if (top==MAX){
  2932. cout<<"Stack is full !"<<endl;
  2933. return;
  2934. };
  2935. num[top]=x;
  2936. top++;
  2937. }
  2938. float pop(void) //出栈函数
  2939. {
  2940. top--;
  2941. if (top<0){
  2942. cout<<"Stack is underflow !"<<endl;
  2943. return 0;
  2944. };
  2945. return num[top];
  2946. }
  2947. }
  2948. //以下是main()函数,其用stack类创建栈对象,并使用了这些对象
  2949. main(void)
  2950. {
  2951. //声明变量和对象
  2952. int i;
  2953. float x;
  2954. stack a('a'),b('b'); //声明(创建)栈对象并初始化
  2955. //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈
  2956. for (i=1; i<=MAX; i++)
  2957. a.push(2.0*i);
  2958. //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示
  2959. for (i=1; i<=MAX; i++)
  2960. cout<<a.pop()<<" ";
  2961. cout<<endl;
  2962. }
  2963. #include<iostream.h>
  2964. main()
  2965. {
  2966. //定义一个名为student的类
  2967. class student {
  2968. int num;
  2969. char *name;
  2970. float grade;
  2971. public:
  2972. //定义构造函数
  2973. student(int n,char *p,float g): num(n),name(p),grade(g){}
  2974. display(void) {
  2975. cout<<num<<" ,"<<name<<","<<grade<<endl;
  2976. }
  2977. };
  2978. student a(1001,"Liming",95),b(1002,"ZhangHua",96.5); //创建对象,并初始化
  2979. //student c; 错误,没提供参数
  2980. a.display(); //显示对象a中的数据
  2981. b.display(); //显示对象b中的数据
  2982. }
  2983. #include <iostream.h>
  2984. #include <stdlib.h>
  2985. //定义timer类
  2986. class timer{
  2987. long minutes;
  2988. public:
  2989. //无参数构造函数
  2990. timer(void) {
  2991. minutes =0;
  2992. };
  2993. //字符指针参数的构造函数
  2994. timer(char *m) {
  2995. minutes = atoi(m);
  2996. };
  2997. //整数类型的构造函数
  2998. timer(int h, int m) {
  2999. minutes = 60*h+m ;
  3000. };
  3001. //双精度浮点型构造函数
  3002. timer(double h) {
  3003. minutes = (int) 60*h ;
  3004. };
  3005. long getminutes(void) { return minutes ; };
  3006. };
  3007. //main()函数的定义
  3008. main(void)
  3009. {
  3010. //使用double类型的构造函数创建对象
  3011. timer start(8.30),finish(17.30);
  3012. cout<<"finish(17.30)-start(8.30)=";
  3013. cout<<finish.getminutes()-start.getminutes()<<endl;
  3014. //使用char指针类型的构造函数创建对象
  3015. timer start0("500"),finish0("800"); //创建对象
  3016. cout<<"finish0(\"800\")-start0(\"500\")=";
  3017. cout<<finish0.getminutes()-start0.getminutes()<<endl;
  3018. //使用无参数构造函数和整型构造函数创建对象
  3019. timer start1;
  3020. timer finish1(3,30);
  3021. cout<<"finish1(3,30)-start1=";
  3022. cout<<finish1.getminutes()-start1.getminutes()<<endl;
  3023. return 0;
  3024. }
  3025. #include <iostream.h>
  3026. //定义rect类
  3027. class rect {
  3028. int length;
  3029. int width;
  3030. int area;
  3031. public:
  3032. rect(int l=1,int w=1)
  3033. {
  3034. length=l;
  3035. width=w;
  3036. area=length*width;
  3037. }
  3038. void show_rect(char *name)
  3039. {
  3040. cout<<name<<":"<<endl;
  3041. cout<<"length="<<length<<endl;
  3042. cout<<"width="<<width<<endl;
  3043. cout<<"area="<<area<<endl;
  3044. }
  3045. };
  3046. //测试使用rect类
  3047. void main(void)
  3048. {
  3049. //用rect类创建对象
  3050. rect a;
  3051. rect b(2);
  3052. rect c(2,3);
  3053. //调用对象的函数显示对象中的数据
  3054. a.show_rect("a");
  3055. b.show_rect("b(2)");
  3056. c.show_rect("c(2,3)");
  3057. }
  3058. #include<iostream.h>
  3059. const int MAX=5; //假定栈中最多保存5个数据
  3060. //定义名为stack的具有栈功能的类
  3061. class stack {
  3062. //数据成员
  3063. double num[MAX]; //存放栈数据的数组
  3064. int top; //指示栈顶位置的变量
  3065. public:
  3066. //成员函数
  3067. stack(char *name) //构造函数
  3068. {
  3069. top=0;
  3070. cout<<"Stack "<<name<<" initialized."<<endl;
  3071. }
  3072. ~stack(void) //析构函数
  3073. {
  3074. cout << "Stack destroyed." << endl; //显示信息
  3075. }
  3076. void push(double x) //入栈函数
  3077. {
  3078. if (top==MAX){
  3079. cout<<"Stack is full !"<<endl;
  3080. return;
  3081. };
  3082. num[top]=x;
  3083. top++;
  3084. }
  3085. double pop(void) //出栈函数
  3086. {
  3087. top--;
  3088. if (top<0){
  3089. cout<<"Stack is underflow !"<<endl;
  3090. return 0;
  3091. };
  3092. return num[top];
  3093. }
  3094. }
  3095. //以下是main()函数,其用stack类创建栈对象,并使用了这些对象
  3096. main(void)
  3097. {
  3098. double x;
  3099. //声明(创建)栈对象并初始化
  3100. stack a("a"),b("b");
  3101. //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈
  3102. for (x=1; x<=MAX; x++)
  3103. a.push(2.0*x);
  3104. //以下利用循环和pop()成员函数依次弹出a栈中的数据并显示
  3105. cout<<"a: ";
  3106. for (int i=1; i<=MAX; i++)
  3107. cout<<a.pop()<<" ";
  3108. cout<<endl;
  3109. //从键盘上为b栈输入数据,并显示
  3110. for(i=1;i<=MAX;i++) {
  3111. cout<<i<<" b:";
  3112. cin>>x;
  3113. b.push(x);
  3114. }
  3115. cout<<"b: ";
  3116. for(i=1;i<=MAX;i++)
  3117. cout<<b.pop()<<" ";
  3118. cout<<endl;
  3119. }
  3120. #include<iostream.h>
  3121. #define MAX 5
  3122. //定义stack类接口
  3123. class stack{
  3124. int num[MAX];
  3125. int top;
  3126. public:
  3127. stack(char *name); //构造函数原型
  3128. ~stack(void); //析构函数原型
  3129. void push(int n);
  3130. int pop(void);
  3131. };
  3132. //main()函数测试stack类
  3133. main(void)
  3134. {
  3135. int i,n;
  3136. //声明对象
  3137. stack a("a"),b("b");
  3138. //以下利用循环和push()成员函数将2,4,6,8,10依次入a栈
  3139. for (i=1; i<=MAX; i++)
  3140. a.push(2*i);
  3141. //以下利用循环和pop()成员函数依次弹出a栈中的数据,并显示
  3142. cout<<"a: ";
  3143. for (i=1; i<=MAX; i++)
  3144. cout<<a.pop()<<" ";
  3145. cout<<endl;
  3146. //从键盘上为b栈输入数据,并显示
  3147. for(i=1;i<=MAX;i++) {
  3148. cout<<i<<" b:";
  3149. cin>>n;
  3150. b.push(n);
  3151. }
  3152. cout<<"b: ";
  3153. for(i=1;i<=MAX;i++)
  3154. cout<<b.pop()<<" ";
  3155. cout<<endl;
  3156. return 0;
  3157. }
  3158. //-------------------------
  3159. // stack成员函数的定义
  3160. //-------------------------
  3161. //定义构造函数
  3162. stack::stack(char *name)
  3163. {
  3164. top=0;
  3165. cout << "Stack "<<name<<" initialized." << endl;
  3166. }
  3167. //定义析构函数
  3168. stack::~stack(void)
  3169. {
  3170. cout << "stack destroyed." << endl; //显示信息
  3171. }
  3172. //入栈成员函数
  3173. void stack::push(int n)
  3174. {
  3175. if (top==MAX){
  3176. cout<<"Stack is full !"<<endl;
  3177. return;
  3178. };
  3179. num[top]=n;
  3180. top++;
  3181. }
  3182. //出栈成员函数
  3183. int stack::pop(void)
  3184. {
  3185. top--;
  3186. if (top<0){
  3187. cout<<"Stack is underflow !"<<endl;
  3188. return 0;
  3189. };
  3190. return num[top];
  3191. }
  3192. #include<iostream.h>
  3193. //定义一个全部为public:模式的类
  3194. class ex
  3195. {
  3196. public:
  3197. int value;
  3198. void set(int n) {
  3199. value=n;
  3200. }
  3201. int get(void) {
  3202. return value;
  3203. }
  3204. };
  3205. //测试使用ex类
  3206. main()
  3207. {
  3208. ex a; //创建对象
  3209. //以下通过成员函数访问对象数据
  3210. a.set(100);
  3211. cout<<"a.get()=";
  3212. cout<<a.get()<<endl;
  3213. //以下直接访问对象的数据成员
  3214. a.value=200;
  3215. cout<<"a.value=";
  3216. cout<<a.value<<endl;
  3217. }
  3218. #include <iostream.h>
  3219. // ex_class类接口定义
  3220. class ex_class
  3221. {
  3222. private:
  3223. int iv;
  3224. double dv;
  3225. public:
  3226. ex_class(void);
  3227. ex_class(int n,double x);
  3228. void set_ex_class(int n,double x);
  3229. void show_ex_class(char*);
  3230. };
  3231. //定义ex_class类的构造函数
  3232. ex_class::ex_class(void):iv(1), dv(1.0) { }
  3233. ex_class::ex_class(int n,double x):iv(n), dv(x) { }
  3234. //定义ex_class类的成员函数
  3235. void ex_class::set_ex_class(int n,double x)
  3236. {
  3237. iv=n;
  3238. dv=x;
  3239. }
  3240. void ex_class::show_ex_class(char *name)
  3241. {
  3242. cout<<name<<": "<<endl;
  3243. cout <<"iv=" <<iv<< endl;
  3244. cout <<"dv=" <<dv<< endl;
  3245. }
  3246. //使用ex_class类
  3247. void main(void)
  3248. {
  3249. ex_class obj1;
  3250. obj1.show_ex_class("obj1");
  3251. obj1.set_ex_class(5,5.5);
  3252. obj1.show_ex_class("obj1");
  3253. ex_class obj2(100,3.14);
  3254. obj2.show_ex_class("obj2");
  3255. obj2.set_ex_class(2000,1.732);
  3256. obj2.show_ex_class("obj2");
  3257. }
  3258. #include<iostream.h>
  3259. //定义一个含有static数据成员的类
  3260. class ex
  3261. {
  3262. static int num; //static数据成员
  3263. public:
  3264. ex() {num++;}
  3265. ~ex() {num--;}
  3266. disp_count() {
  3267. cout<<"The current instances count:";
  3268. cout<<num<<endl;
  3269. }
  3270. };
  3271. int ex::num=0; //设置static数据成员的初值
  3272. //main()函数测试ex类
  3273. main()
  3274. {
  3275. ex a;
  3276. a.disp_count();
  3277. ex *p;
  3278. p=new ex;
  3279. p->disp_count();
  3280. ex x[10];
  3281. x[0].disp_count();
  3282. delete p;
  3283. a.disp_count();
  3284. }
  3285. #include<iostream.h>
  3286. //定义一个含有static数据成员的类
  3287. class ex
  3288. {
  3289. static int num; //static数据成员
  3290. public:
  3291. ex() {num++;}
  3292. ~ex() {num--;}
  3293. static disp_count(void) //static成员函数
  3294. {
  3295. cout<<"The current instances count:";
  3296. cout<<num<<endl;
  3297. }
  3298. };
  3299. int ex::num=0; //设置static数据成员的初值
  3300. //main()函数测试ex类
  3301. main()
  3302. {
  3303. ex a;
  3304. a.disp_count();
  3305. ex *p;
  3306. p=new ex;
  3307. p->disp_count();
  3308. ex x[10];
  3309. ex::disp_count(); //直接用类作用域符引用静态成员函数
  3310. delete p;
  3311. ex::disp_count(); //直接用类作用域符引用静态成员函数
  3312. }
  3313. #include <iostream.h>
  3314. class ex_class {
  3315. int value;
  3316. public:
  3317. ex_class(int n) {
  3318. value=n;
  3319. cout << "Stack initialized." << endl;
  3320. }
  3321. ~ex_class() {
  3322. cout << "The Object destroyed." <<endl;
  3323. }
  3324. void set_value(int n);
  3325. void show_val(char *name);
  3326. } ;
  3327. //在类外定义内联成员函数
  3328. inline void ex_class::set_value(int n) {
  3329. value=n;
  3330. }
  3331. //在类外定义非内联成员函数
  3332. void ex_class::show_val(char *name) {
  3333. cout<<name<<": ";
  3334. cout<<value<<endl;
  3335. }
  3336. //在main()函数中测试ex_class类
  3337. main(void)
  3338. {
  3339. //创建对象x和y
  3340. ex_class x(100),y(200);
  3341. //显示对象的数据
  3342. x.show_val("x");
  3343. y.show_val("y");
  3344. //设置新值给对象
  3345. x.set_value(1);
  3346. y.set_value(2);
  3347. //显示对象的数据
  3348. x.show_val("x");
  3349. y.show_val("y");
  3350. return 0;
  3351. }
  3352. #include <iostream.h>
  3353. //定义空类empty
  3354. class empty
  3355. {
  3356. };
  3357. //在main()函数中用空类创建对象
  3358. main()
  3359. {
  3360. empty a,*p; //编译通过
  3361. cout<<"Test a empty class."<<endl;
  3362. }
  3363. #include<iostream.h>
  3364. //用struct关键字定义ex_class类
  3365. struct ex_class {
  3366. ex_class(int n=1): value(n) {}
  3367. void set_value(int n) {
  3368. value=n;
  3369. }
  3370. show_obj(char *name) {
  3371. cout<<name<<": "<<value<<endl;
  3372. }
  3373. private:
  3374. int value;
  3375. }
  3376. //测试 ex_class类
  3377. main()
  3378. {
  3379. //用ex_class创建对象
  3380. ex_class a,b(3);
  3381. a.show_obj("a");
  3382. b.show_obj("b");
  3383. a.set_value(100);
  3384. b.set_value(200);
  3385. a.show_obj("a");
  3386. b.show_obj("b");
  3387. }
  3388. #include <iostream.h>
  3389. #include<string.h>
  3390. //定义双亲(parent)类
  3391. class parent {
  3392. char f_name[20];
  3393. char m_name[20];
  3394. char tel[10];
  3395. public:
  3396. // parent类的构造函数,其带有缺省值
  3397. parent(char *p1="",char *p2="",char *p3="") {
  3398. strcpy(f_name,p1);
  3399. strcpy(m_name,p2);
  3400. strcpy(tel,p3);
  3401. }
  3402. //显示parent对象的数据
  3403. show_parent(void) {
  3404. cout<<"The parent:"<<endl;
  3405. cout<<" father's name:"<<f_name<<endl;
  3406. cout<<" mother's name:"<<m_name<<endl;
  3407. cout<<" tel:"<<tel<<endl;
  3408. }
  3409. };
  3410. //定义student类
  3411. class student {
  3412. int num;
  3413. char name[20];
  3414. float grade;
  3415. parent pt;
  3416. public:
  3417. // student类的构造函数
  3418. student(int n,char *str,float g,class parent t) {
  3419. num=n;
  3420. strcpy(name,str);
  3421. grade=g;
  3422. pt=t;
  3423. }
  3424. //显示student对象的数据
  3425. show_student(void) {
  3426. cout<<"num:"<<num<<endl;
  3427. cout<<"name:"<<name<<endl;
  3428. cout<<"grade:"<<grade<<endl;
  3429. pt.show_parent();
  3430. }
  3431. };
  3432. //main()函数测试student类的对象
  3433. main(void)
  3434. {
  3435. //创建双亲对象
  3436. parent p1("ZhangHua","LiLan","83665215");
  3437. //创建学生对象
  3438. student st(10001,"ZhangHui",91.5,p1);
  3439. //显示学生信息
  3440. cout<<"p1:"<<endl;
  3441. p1.show_parent();
  3442. //显示学生信息
  3443. cout<<"st:"<<endl;
  3444. st.show_student();
  3445. }
  3446. #include <iostream.h>
  3447. #include <stdlib.h>
  3448. //定义timer类
  3449. class timer{
  3450. long minutes;
  3451. public:
  3452. //定义重载成员函数
  3453. settimer(char *m) {
  3454. minutes = atoi(m);
  3455. };
  3456. //定义重载成员函数
  3457. settimer(int h, int m) {
  3458. minutes = 60*h+m ;
  3459. };
  3460. //定义重载成员函数
  3461. settimer(double h) {
  3462. minutes = (int) 60*h ;
  3463. };
  3464. long getminutes(void) { return minutes; };
  3465. };
  3466. //main()函数的定义
  3467. main(void){
  3468. timer start,finish; //创建对象
  3469. //使用重载成员函数
  3470. start.settimer(8,30);
  3471. finish.settimer(9,40);
  3472. cout<<"finish.settimer(9,40)-start.settimer(8,30):";
  3473. cout<<finish.getminutes()-start.getminutes()<<endl;
  3474. //使用重载成员函数
  3475. start.settimer(2.0);
  3476. finish.settimer("180");
  3477. cout<<"finish.settimer(\"180\")-start.settimer(2.0):";
  3478. cout<<finish.getminutes()-start.getminutes()<<endl;
  3479. return 0;
  3480. }
  3481. #include <iostream.h>
  3482. //定义复数类
  3483. class complex{
  3484. float real; //实部
  3485. float image; //虚部
  3486. public:
  3487. //重载的运算符"+"的原型
  3488. complex operator+ (complex right);
  3489. //重载赋值运算符"="的定义
  3490. complex operator= (complex right);
  3491. void set_complex(float re, float im);
  3492. void put_complex(char *name);
  3493. };
  3494. //重载加法运算符"+"的定义
  3495. complex complex::operator+ (complex right) {
  3496. complex temp;
  3497. temp.real = this->real + right.real;
  3498. temp.image = this->image + right.image;
  3499. return temp;
  3500. }
  3501. //重载加赋值运算符"="的定义
  3502. complex complex::operator= (complex right) {
  3503. this->real = right.real;
  3504. this->image = right.image;
  3505. return *this;
  3506. }
  3507. //定义set_complex()成员函数
  3508. void complex::set_complex(float re, float im) {
  3509. real = re;
  3510. image = im;
  3511. }
  3512. //定义put_complex()成员函数
  3513. void complex::put_complex(char *name) {
  3514. cout<<name<<": ";
  3515. cout << real << ' ';
  3516. if (image >= 0.0 ) cout << '+';
  3517. cout << image << "i\n";
  3518. }
  3519. //在main()函数中使用complex类的对象
  3520. main(void)
  3521. {
  3522. complex A, B, C; //创建复数对象
  3523. //设置复数变量的值
  3524. A.set_complex(1.2, 0.3);
  3525. B.set_complex(-0.5, -0.8);
  3526. //显示复数数据
  3527. A.put_complex("A");
  3528. B.put_complex("B");
  3529. //赋值运算,显示结果
  3530. C = A;
  3531. C.put_complex("C=A");
  3532. //加法及赋值运算,显示结果
  3533. C = A + B;
  3534. C.put_complex("C=A+B");
  3535. return 0;
  3536. }
  3537. // Example of the friend class
  3538. #include <iostream.h>
  3539. //定义YourClass类,
  3540. class YourClass
  3541. {
  3542. //指定YourOtherClass是它的友元类
  3543. friend class YourOtherClass;
  3544. private:
  3545. int num;
  3546. public:
  3547. YourClass(int n){num=n;}
  3548. display(char *YCname){
  3549. cout<<YCname<<".num :";
  3550. cout<<num<<endl;
  3551. }
  3552. };
  3553. //定义YourOtherClass,它是YourClass类的友元类
  3554. class YourOtherClass
  3555. {
  3556. public:
  3557. //使用YourClass类的私有成员
  3558. void disp1(YourClass yc,char *YCname){
  3559. cout<<YCname<<".num :";
  3560. cout<<yc.num<<endl;
  3561. }
  3562. //使用YourClass类的公共成员
  3563. void disp2(YourClass yc,char* YCname){
  3564. yc.display(YCname);
  3565. }
  3566. };
  3567. //在main()函数中创建和使用YourClass和YourOtherClass类对象
  3568. main(void)
  3569. {
  3570. //声明YourClass类对象
  3571. YourClass a(10),b(100);
  3572. //显示a和b对象的值
  3573. cout<<"YourClass:"<<endl;
  3574. a.display("a");
  3575. b.display("b");
  3576. //声明YourOtherClass类对象
  3577. YourOtherClass temp;
  3578. //通过temp显示a和b对象的值
  3579. cout<<"YourOtherClass:"<<endl;
  3580. temp.disp1(a,"a");
  3581. temp.disp2(b,"b");
  3582. }
  3583. #include<iostream.h>
  3584. //Y类的不完全定义
  3585. class Y;
  3586. //X类的定义
  3587. class X {
  3588. public:
  3589. void disp(Y py,char *name); //成员函数原型
  3590. };
  3591. //定义Y类
  3592. class Y {
  3593. //声明本类的友元函数
  3594. //X类的disp()为本例的友元函数
  3595. friend void X::disp(Y py,char *name);
  3596. //普通函数putY() 为本例的友元函数
  3597. friend void putY(Y& yc,char *name);
  3598. private: //私有成员
  3599. int num;
  3600. dispY(char *name){
  3601. cout<<name<<".num="<<num<<endl;
  3602. }
  3603. public: //公共成员函数
  3604. Y(int n){
  3605. num=n;
  3606. }
  3607. };
  3608. //X类成员函数的实现部分
  3609. void X::disp(Y py,char *name){
  3610. cout<<"In X::disp():"<<endl;
  3611. py.dispY(name); //访问Y类的私有函数
  3612. }
  3613. //普通函数putY()的定义
  3614. void putY(Y& yc,char *name){
  3615. cout<<"In getY:"<<endl;
  3616. yc.dispY(name);
  3617. cout<<name<<".num=";
  3618. cout<<yc.num<<endl;
  3619. }
  3620. //在main()函数测试X和Y类的功能
  3621. main()
  3622. {
  3623. //创建Y和X类的对象
  3624. Y y1(100),y2(200);
  3625. X x;
  3626. //不可用Y类对象的私有成员函数显示
  3627. //y1.dispY("y1");
  3628. //y2.dispY("y2");
  3629. //调用X类对象的友元函数显示
  3630. x.disp(y1,"y1");
  3631. x.disp(y2,"y2");
  3632. //用getY函数显示Y类的对象显示
  3633. putY(y1,"y1");
  3634. putY(y2,"y2");
  3635. }
  3636. #include <iostream.h>
  3637. //定义日期类
  3638. class Date
  3639. {
  3640. //定义友元重载输入运算符函数
  3641. friend istream& operator >> (istream& input,Date& dt );
  3642. //定义友元重载输出运算符函数
  3643. friend ostream& operator<< (ostream& output,Date& dt );
  3644. int mo, da, yr;
  3645. public:
  3646. Date(void){ //无参数构造函数
  3647. yr = 0;
  3648. mo = 0;
  3649. da = 0;
  3650. }
  3651. Date( int y, int m, int d ) //带参数构造函数
  3652. {
  3653. yr = y;
  3654. mo = m;
  3655. da = d;
  3656. }
  3657. };
  3658. //定义">>"运算符重载函数
  3659. istream& operator >> ( istream& input, Date& dt )
  3660. {
  3661. cout<<"Year:";
  3662. input>>dt.yr;
  3663. cout<<"Month:";
  3664. input>>dt.mo;
  3665. cout<<"Day:";
  3666. input>>dt.da;
  3667. return input;
  3668. }
  3669. //定义"<<"运算符重载函数
  3670. ostream& operator<< ( ostream& output, Date& dt )
  3671. {
  3672. output<< dt.yr << '/' << dt.mo << '/' << dt.da<<endl;
  3673. return output;
  3674. }
  3675. //在main()函数中测试Date类的插入(<<)和提取(>>)运算符
  3676. void main()
  3677. {
  3678. //声明对象
  3679. Date dt1(2002,5,1),dt2;
  3680. //显示dt1对象
  3681. cout<<dt1;
  3682. //对dt2对象进行输入和输出
  3683. cin>>dt2;
  3684. cout<<dt2;
  3685. }
  3686. #include<iostream.h>
  3687. //定义ex类
  3688. class ex_class
  3689. {
  3690. int a;
  3691. double b;
  3692. public:
  3693. ex_class(int n=1,double x=1.0):a(n),b(x) {}
  3694. void show_value(char *name) {
  3695. cout<<name<<" :"<<endl;
  3696. cout<<"a="<<a<<endl;
  3697. cout<<"b="<<b<<endl;
  3698. }
  3699. };
  3700. //定义main()函数
  3701. main()
  3702. {
  3703. //创建ex_class的对象并显示
  3704. ex_class obj1,obj2(100,3.5);
  3705. obj1.show_value("obj1");
  3706. obj2.show_value("obj2");
  3707. //创建ex_class的指针变量
  3708. ex_class *p;
  3709. //p指向obj1并显示
  3710. p=&obj1;
  3711. p->show_value("p->obj1");
  3712. //p指向obj2并显示
  3713. p=&obj2;
  3714. (*p).show_value("(*p)obj2");
  3715. //p指向动态创建的对象并显示
  3716. p=new ex_class;
  3717. p->show_value("p->new");
  3718. delete p; //删除对象
  3719. }
  3720. #include<iostream.h>
  3721. //基类Box
  3722. class Box {
  3723. int width,height;
  3724. public:
  3725. void SetWidth(int w) {
  3726. width=w;
  3727. }
  3728. void SetHeight(int h) {
  3729. height=h;
  3730. }
  3731. int GetWidth() {return width;}
  3732. int GetHeight() {return height;}
  3733. };
  3734. //派生类ColoredBox
  3735. class ColoredBox:public Box
  3736. {
  3737. int color;
  3738. public:
  3739. void SetColor(int c){
  3740. color=c;
  3741. }
  3742. int GetColor() {return color;}
  3743. };
  3744. // 在main()中测试基类和派生类
  3745. main(void)
  3746. {
  3747. //声明并使用ColoredBox类的对象
  3748. ColoredBox cbox;
  3749. cbox.SetColor(3); //使用自己的成员函数
  3750. cbox.SetWidth(150); //使用基类的成员函数
  3751. cbox.SetHeight(100); //使用基类的成员函数
  3752. cout<<"cbox:"<<endl;
  3753. cout<<"Color:"<<cbox.GetColor()<<endl; //使用自己的成员函数
  3754. cout<<"Width:"<<cbox.GetWidth()<<endl; //使用基类的成员函数
  3755. cout<<"Height:"<<cbox.GetHeight()<<endl; //使用基类的成员函数
  3756. //cout<<cbox.width; Error!
  3757. }
  3758. #include<iostream.h>
  3759. //基类First
  3760. class First {
  3761. int val1;
  3762. public:
  3763. SetVal1(int v) {
  3764. val1=v;
  3765. }
  3766. void show_First(void) {
  3767. cout<<"val1="<<val1<<endl;
  3768. }
  3769. };
  3770. //派生类Second
  3771. class Second:private First { //默认为private模式
  3772. int val2;
  3773. public:
  3774. void SetVal2(int v1,int v2) {
  3775. SetVal1(v1); //可见,合法
  3776. val2=v2;
  3777. }
  3778. void show_Second(void) {
  3779. // cout<<"val1="<<val1<<endl; 不能访问First私有成员
  3780. show_First();
  3781. cout<<"val2="<<val2<<endl;
  3782. }
  3783. };
  3784. main() {
  3785. Second s1;
  3786. //s1.SetVal1(1); //不可见,非法
  3787. s1.SetVal2(2,3); //合法
  3788. //s1.show_First(); //不可见,非法
  3789. s1.show_Second();
  3790. }
  3791. #include<iostream.h>
  3792. //基类First
  3793. class First {
  3794. int val1;
  3795. public:
  3796. SetVal1(int v) {
  3797. val1=v;
  3798. }
  3799. void show_First(void) {
  3800. cout<<"val1="<<val1<<endl;
  3801. }
  3802. };
  3803. //派生类Second
  3804. class Second:public First { //默认为private模式
  3805. int val2;
  3806. public:
  3807. void SetVal2(int v1,int v2) {
  3808. SetVal1(v1); //可见,合法
  3809. val2=v2;
  3810. }
  3811. void show_Second(void) {
  3812. // cout<<"val1="<<val1<<endl; 不能访问First私有成员
  3813. show_First();
  3814. cout<<"val2="<<val2<<endl;
  3815. }
  3816. };
  3817. main() {
  3818. Second s1;
  3819. //调用Second类定义的成员函数
  3820. s1.SetVal2(2,3);
  3821. cout<<"s1.show_Second():"<<endl;
  3822. s1.show_Second();
  3823. //调用First类定义的成员函数
  3824. s1.SetVal1(10);
  3825. cout<<"s1.show_First():"<<endl;
  3826. s1.show_First();
  3827. }
  3828. #include<iostream.h>
  3829. //定义最低层基类,它作为其他类的基类
  3830. class First {
  3831. int val1;
  3832. public:
  3833. First(void) {
  3834. cout<<"The First initialized"<<endl;
  3835. }
  3836. };
  3837. //定义派生类,它作为其他类的基类
  3838. class Second :public First {
  3839. int val2;
  3840. public:
  3841. Second(void) {
  3842. cout<<"The Second initialized"<<endl;
  3843. }
  3844. };
  3845. //定义最上层派生类
  3846. class Three :public Second {
  3847. int val3;
  3848. public:
  3849. Three() {
  3850. cout<<"The Three initialized"<<endl;
  3851. }
  3852. };
  3853. //定义各基类的对象,测试构造函数的执行情况
  3854. //定义各基类的对象,测试构造函数的执行情况
  3855. main() {
  3856. cout<<"First f1;"<<endl;
  3857. First f1;
  3858. cout<<"Second s1;"<<endl;
  3859. Second s1;
  3860. cout<<"Three t1;"<<endl;
  3861. Three t1;
  3862. }
  3863. #include<iostream.h>
  3864. //定义基类First
  3865. class First {
  3866. int num;
  3867. float grade;
  3868. public:
  3869. //构造函数带参数
  3870. First(int n,float v ) : num(n),grade(v)
  3871. {
  3872. cout<<"The First initialized"<<endl;
  3873. }
  3874. DispFirst(void) {
  3875. cout<<"num="<<num<<endl;
  3876. cout<<"grade="<<grade<<endl;
  3877. }
  3878. };
  3879. //定义派生类Second
  3880. class Second :public First {
  3881. double val;
  3882. public:
  3883. //无参数构造函数,要为基类的构造函数设置参数
  3884. Second(void):First(10000,0) {
  3885. val=1.0;
  3886. cout<<"The Second initialized"<<endl;
  3887. }
  3888. //带参数构造函数,为基类的构造函数设置参数
  3889. Second(int n,float x,double dx):First(n,x) {
  3890. val=dx;
  3891. cout<<"The Second initialized"<<endl;
  3892. }
  3893. Disp(char *name){
  3894. cout<<name<<".val="<<val<<endl;
  3895. DispFirst();
  3896. }
  3897. };
  3898. //main()函数中创建和使用派生类对象
  3899. main() {
  3900. //调用派生类的无参数构造函数
  3901. cout<<"Second s1;"<<endl;
  3902. Second s1;
  3903. cout<<"s1.Disp(\"s1\");"<<endl;
  3904. s1.Disp("s1");
  3905. //调用派生类的有参数构造函数
  3906. cout<<"Second s2(10002,95.7,3.1415926); "<<endl;
  3907. Second s2(10002,95.7,3.1415926);
  3908. cout<<"s2.Disp(\"s2\");"<<endl;
  3909. s2.Disp("s2");
  3910. }
  3911. #include<iostream.h>
  3912. //定义最低层基类First,它作为其他类的基类
  3913. class First {
  3914. int val1;
  3915. public:
  3916. First() {
  3917. cout<<"The First initialized"<<endl;
  3918. }
  3919. ~First() {
  3920. cout<<"The First destroyed"<<endl;
  3921. }
  3922. };
  3923. //定义派生类Second,它作为其他类的基类
  3924. class Second :public First { //默认为private模式
  3925. int val2;
  3926. public:
  3927. Second() {
  3928. cout<<"The Second initialized"<<endl;
  3929. }
  3930. ~Second() {
  3931. cout<<"The Second destroyed"<<endl;
  3932. }
  3933. };
  3934. //定义最上层派生类Three
  3935. class Three :public Second {
  3936. int val3;
  3937. public:
  3938. Three() {
  3939. cout<<"The Three initialized"<<endl;
  3940. }
  3941. ~Three() {
  3942. cout<<"The Three destroyed"<<endl;
  3943. }
  3944. };
  3945. //main()函数中测试构造函数和析构函数的执行情况
  3946. main() {
  3947. Three t1;
  3948. cout<<"---- Use the t1----"<<endl;
  3949. }
  3950. #include<iostream.h>
  3951. //基类
  3952. class First {
  3953. int val1;
  3954. protected:
  3955. void SetVal1(int v) {
  3956. val1=v;
  3957. }
  3958. public:
  3959. show_First(void) {
  3960. cout<<"val1="<<val1<<endl;
  3961. }
  3962. };
  3963. //派生类
  3964. class Second:public First {
  3965. int val2;
  3966. protected:
  3967. void SetVal2(int v) {
  3968. SetVal1(v); //使用First 基类的保护成员
  3969. val2=v;
  3970. }
  3971. public:
  3972. show_Second(void) {
  3973. show_First();
  3974. cout<<"val2="<<val2<<endl;
  3975. }
  3976. };
  3977. //派生类
  3978. class Third:public Second {
  3979. int val3;
  3980. public:
  3981. void SetVal3(int n) {
  3982. SetVal1(n); //使用First 基类的保护成员
  3983. SetVal2(n); //使用Second基类的保护成员
  3984. val3=n;
  3985. }
  3986. show_Third(void) {
  3987. show_Second();
  3988. cout<<"val3="<<val3<<endl;
  3989. }
  3990. };
  3991. //main()函数的定义
  3992. main(void)
  3993. {
  3994. First f1;
  3995. //f1.SetVal1(1); 不可访问
  3996. Second s1;
  3997. //s1.SetVal1(1); 不可访问
  3998. //s1.SetVal2(2); 不可访问
  3999. Third t1;
  4000. //t1.SetVal1(1); 不可访问
  4001. //t1.SetVal2(2); 不可访问
  4002. t1.SetVal3(10);
  4003. //显示t1对象的数据
  4004. cout<<"t1.show_Third();"<<endl;
  4005. t1.show_Third();
  4006. cout<<"t1.show_Second();"<<endl;
  4007. t1.show_Second();
  4008. cout<<"t1.show_First();"<<endl;
  4009. t1.show_First();
  4010. }
  4011. #include <iostream.h>
  4012. enum Color {Red,Yellow,Green,White};
  4013. //圆类Circle的定义
  4014. class Circle {
  4015. float radius;
  4016. public:
  4017. Circle(float r) {radius=r;}
  4018. float Area() {
  4019. return 3.1416*radius*radius;
  4020. }
  4021. };
  4022. //桌子类Table的定义
  4023. class Table {
  4024. float height;
  4025. public:
  4026. Table(float h) {height=h;}
  4027. float Height() {
  4028. return height;
  4029. }
  4030. };
  4031. //圆桌类RoundTable的定义
  4032. class RoundTable:public Table,public Circle {
  4033. Color color;
  4034. public:
  4035. RoundTable(float h,float r,Color c); //构造函数
  4036. int GetColor() {
  4037. return color;
  4038. }
  4039. };
  4040. //圆桌构造函数的定义
  4041. RoundTable::RoundTable(float h,float r,Color c):Table(h),Circle(r)
  4042. {
  4043. color=c;
  4044. }
  4045. //main()函数的定义
  4046. main() {
  4047. RoundTable cir_table(15.0,2.0,Yellow);
  4048. cout<<"The table properties are:"<<endl;
  4049. //调用Height类的成员函数
  4050. cout<<"Height="<<cir_table.Height()<<endl;
  4051. //调用circle类的成员函数
  4052. cout<<"Area="<<cir_table.Area()<<endl;
  4053. //调用RoundTable类的成员函数
  4054. cout<<"Color="<<cir_table.GetColor()<<endl;
  4055. }
  4056. #include <iostream.h>
  4057. //定义一个枚举类型
  4058. enum Color {Red,Yellow,Green,White};
  4059. //圆类Circle的定义
  4060. class Circle {
  4061. float radius;
  4062. public:
  4063. Circle(float r) {
  4064. radius=r;
  4065. cout<<"Circle initialized!"<<endl;
  4066. }
  4067. ~Circle() { //析构函数
  4068. cout<<"Circle destroyed!"<<endl;
  4069. }
  4070. float Area() {
  4071. return 3.1416*radius*radius;
  4072. }
  4073. };
  4074. //桌子类Table的定义
  4075. class Table {
  4076. float height;
  4077. public:
  4078. Table(float h) {
  4079. height=h;
  4080. cout<<"Table initialized!"<<endl;
  4081. }
  4082. ~Table() { //构造函数
  4083. cout<<"Table destroyed!"<<endl;
  4084. }
  4085. float Height() {
  4086. return height;
  4087. }
  4088. };
  4089. //圆桌类RoundTable的定义
  4090. class RoundTable:public Table,public Circle {
  4091. Color color;
  4092. public:
  4093. RoundTable(float h,float r,Color c); //构造函数
  4094. int GetColor() {
  4095. return color;
  4096. }
  4097. ~RoundTable() { //构造函数
  4098. cout<<"RoundTable destroyed!"<<endl;
  4099. }
  4100. };
  4101. //圆桌构造函数的定义
  4102. RoundTable::RoundTable(float h,float r,Color c):Table(h),Circle(r)
  4103. {
  4104. color=c;
  4105. cout<<"RoundTable initialized!"<<endl;
  4106. }
  4107. //测试多继承中构造函数和析构函数的执行方式
  4108. main() {
  4109. RoundTable cir_table(15.0,2.0,Yellow);
  4110. cout<<"The table properties are:"<<endl;
  4111. //调用Height类的成员函数
  4112. cout<<"Height="<<cir_table.Height()<<endl;
  4113. //调用circle类的成员函数
  4114. cout<<"Area="<<cir_table.Area()<<endl;
  4115. //调用RoundTable类的成员函数
  4116. cout<<"Color="<<cir_table.GetColor()<<endl;
  4117. }
  4118. #include<iostream.h>
  4119. //定义有两个虚函数的基类
  4120. class Base {
  4121. public:
  4122. //定义两个虚函数
  4123. virtual void aFn1(void){
  4124. cout<<"aFnl is in Base class."<<endl;
  4125. }
  4126. virtual void aFn2(void) {
  4127. cout<<"aFn2 is in Base class."<<endl;
  4128. }
  4129. //定义非虚函数
  4130. void aFn3(void) {
  4131. cout<<"aFn3 is in Base class."<<endl;
  4132. }
  4133. };
  4134. //派生类Derived_1中重新定义了基类中的虚函数aFn1
  4135. class Derived_1:public Base
  4136. {
  4137. public:
  4138. void aFn1(void) { //覆盖aFn1()函数
  4139. cout<<"aFnl is in First derived class."<<endl;
  4140. }
  4141. // void aFn3(void) { 语法错误
  4142. // cout<<"aFn3 is in First derived class."<<endl;
  4143. //}
  4144. };
  4145. //派生类Derived_2中重新定义了基类中的虚函数aFn2
  4146. class Derived_2:public Base{
  4147. public:
  4148. void aFn2(void){ //覆盖aFn2()函数
  4149. cout<<"aFn2 is in Second derived class."<<endl;
  4150. }
  4151. // void aFn3(void) { 语法错误
  4152. // cout<<"aFn3 is in Second derived class."<<endl;
  4153. //}
  4154. };
  4155. //main()函数的定义
  4156. main(void)
  4157. {
  4158. //创建和使用基类Base的对象
  4159. Base b;
  4160. cout<<"Base:"<<endl;
  4161. b.aFn1();
  4162. b.aFn2();
  4163. b.aFn3();
  4164. cout<<"----------------------"<<endl;
  4165. //创建和使用派生类Derived_1的对象
  4166. Derived_1 d1;
  4167. cout<<"Derived_1:"<<endl;
  4168. d1.aFn1();
  4169. d1.aFn2();
  4170. d1.aFn3();
  4171. cout<<"----------------------"<<endl;
  4172. //创建和使用派生类Derived_2的对象
  4173. Derived_2 d2;
  4174. cout<<"Derived_2:"<<endl;
  4175. d2.aFn1();
  4176. d2.aFn2();
  4177. d2.aFn3();
  4178. }
  4179. #include<iostream.h>
  4180. //定义抽象类
  4181. class Base {
  4182. public:
  4183. //定义两个纯虚函数
  4184. virtual void aFn1(void)=0;
  4185. virtual void aFn2(void)=0;
  4186. };
  4187. //派生类Derived_1中覆盖了基类中的纯虚函数
  4188. class Derived_1:public Base
  4189. {
  4190. public:
  4191. void aFn1(void) {
  4192. cout<<"aFnl is in First derived class."<<endl;
  4193. }
  4194. void aFn2(void) {
  4195. cout<<"aFn2 is in First derived class."<<endl;
  4196. }
  4197. };
  4198. //派生类Derived_2中覆盖了基类中的纯虚函数
  4199. class Derived_2:public Base{
  4200. public:
  4201. virtual void aFn1(void){
  4202. cout<<"aFn1 is in Second derived class."<<endl;
  4203. }
  4204. void aFn2(void){
  4205. cout<<"aFn2 is in Second derived class."<<endl;
  4206. }
  4207. };
  4208. //main()函数中测试抽象类及其派生类的对象
  4209. main(void)
  4210. {
  4211. //用抽象类不能创建对象
  4212. // Base b; 语法错误
  4213. // b.aFn1();
  4214. // b.aFn2();
  4215. //创建和使用Derived_1类的对象
  4216. Derived_1 d1;
  4217. cout<<"Derived_1 d1:"<<endl;
  4218. d1.aFn1();
  4219. d1.aFn2();
  4220. cout<<"------------------"<<endl;
  4221. //创建和使用Derived_2类的对象
  4222. Derived_2 d2;
  4223. cout<<"Derived_2 d2:"<<endl;
  4224. d2.aFn1();
  4225. d2.aFn2();
  4226. }
  4227. #include<iostream.h>
  4228. int extract_int()
  4229. {
  4230. char ch;
  4231. int n=0;
  4232. while(ch=cin.get())
  4233. if (ch>='0' && ch<='9')
  4234. {
  4235. cin.putback(ch);
  4236. cin>>n;
  4237. break;
  4238. }
  4239. return n;
  4240. }
  4241. //main()函数
  4242. main(void)
  4243. {
  4244. //提取字符串中的数字
  4245. int a=extract_int();
  4246. int b=extract_int();
  4247. int c=extract_int();
  4248. //显示结果
  4249. cout<<a<<"+"<<b<<"="<<c<<endl;
  4250. }
  4251. #include<iostream.h>
  4252. //定义节点(数据对象)的接口
  4253. class Node
  4254. {
  4255. //声明list类为本类的友元类
  4256. friend class list;
  4257. //私有成员
  4258. private:
  4259. int Data; //节点数据
  4260. Node *previous; //前趋指针
  4261. Node *next; //后继指针
  4262. };
  4263. //定义双向链表list的接口声明
  4264. class list
  4265. {
  4266. //私有成员
  4267. private:
  4268. Node *Head; //链表头指针
  4269. Node *Tail; //链表尾指针
  4270. //定义接口函数
  4271. public:
  4272. //构造函数
  4273. list();
  4274. //析构函数
  4275. ~list();
  4276. //从链表尾后添加数据
  4277. void Build_HT(int Data);
  4278. //从链表前头添加数据
  4279. void Build_TH(int Data);
  4280. //从头到尾显示数据
  4281. void list::Display_HT();
  4282. //从尾到头显示数据
  4283. void list::Display_TH();
  4284. //清除链表的全部数据
  4285. void Clear();
  4286. };
  4287. //main()函数测试双向链表
  4288. int main(void)
  4289. {
  4290. list list1;
  4291. int i;
  4292. //从尾添加数据
  4293. cout<<"Add to the back of the list1:"<<endl;
  4294. for (i=1;i<=20;i=i+2) {
  4295. list1.Build_HT(i);
  4296. cout<<i<<" ";
  4297. }
  4298. cout<<endl;
  4299. //从头添加数据
  4300. cout<<"Add to the front of the list1:"<<endl;
  4301. for (i=0;i<=20;i=i+2) {
  4302. list1.Build_TH(i);
  4303. cout<<i<<" ";
  4304. }
  4305. cout<<endl;
  4306. //显示链表
  4307. list1.Display_HT();
  4308. list1.Display_TH();
  4309. return 0;
  4310. }
  4311. //list类函数的定义
  4312. //构造函数的定义
  4313. list::list()
  4314. {
  4315. //初值
  4316. Head=0;
  4317. Tail=0;
  4318. }
  4319. //析构函数的定义
  4320. list::~list()
  4321. {
  4322. Clear();
  4323. }
  4324. //从链表尾后添加数据
  4325. void list::Build_HT(int Data)
  4326. {
  4327. Node *Buffer;
  4328. Buffer=new Node;
  4329. Buffer->Data=Data;
  4330. if(Head==0)
  4331. {
  4332. Head=Buffer;
  4333. Head->next=0;
  4334. Head->previous=0;
  4335. Tail=Head;
  4336. }
  4337. else
  4338. {
  4339. Tail->next=Buffer;
  4340. Buffer->previous=Tail;
  4341. Buffer->next=0;
  4342. Tail=Buffer;
  4343. }
  4344. }
  4345. //从链表前头添加数据
  4346. void list::Build_TH(int Data)
  4347. {
  4348. Node *NewNode;
  4349. NewNode=new Node;
  4350. NewNode->Data=Data;
  4351. if(Tail==0)
  4352. {
  4353. Tail=NewNode;
  4354. Tail->next=0;
  4355. Tail->previous=0;
  4356. Head=Tail;
  4357. }
  4358. else
  4359. {
  4360. NewNode->previous=0;
  4361. NewNode->next=Head;
  4362. Head->previous=NewNode;
  4363. Head=NewNode;
  4364. }
  4365. }
  4366. //从头到尾显示数据
  4367. void list::Display_HT()
  4368. {
  4369. Node *TEMP;
  4370. TEMP=Head;
  4371. cout<<"Display the list from Head to Tail:"<<endl;
  4372. while(TEMP!=0)
  4373. {
  4374. cout<<TEMP->Data<<" ";
  4375. TEMP=TEMP->next;
  4376. }
  4377. cout<<endl;
  4378. }
  4379. //从尾到头显示数据
  4380. void list::Display_TH()
  4381. {
  4382. Node *TEMP;
  4383. TEMP=Tail;
  4384. cout<<"Display the list from Tail to Head:"<<endl;
  4385. while(TEMP!=0)
  4386. {
  4387. cout<<TEMP->Data<<" ";
  4388. TEMP=TEMP->previous;
  4389. }
  4390. cout<<endl;
  4391. }
  4392. //清除链表的全部数据
  4393. void list::Clear()
  4394. {
  4395. Node *Temp_head=Head;
  4396. if (Temp_head==0) return;
  4397. do
  4398. {
  4399. Node *TEMP_NODE=Temp_head;
  4400. Temp_head=Temp_head->next;
  4401. delete TEMP_NODE;
  4402. }
  4403. while (Temp_head!=0);
  4404. }
  4405. #include <iostream>
  4406. #include <string>
  4407. using namespace std;
  4408. //测试字符串(string)对象
  4409. void main()
  4410. {
  4411. //创建string对象,并显示
  4412. string s1;
  4413. string s2="ABCDEFGHIJK";
  4414. string s3=s2;
  4415. string s4(20,'A');
  4416. string s5(s2,3,3);
  4417. cout<<"s1="<<s1<<endl;
  4418. cout<<"s2="<<s2<<endl;
  4419. cout<<"s3="<<s3<<endl;
  4420. cout<<"s4="<<s4<<endl;
  4421. cout<<"s5="<<s5<<endl;
  4422. //为string对象输入数据,并显示
  4423. cout<<"s1=";
  4424. cin>>s1;
  4425. cout<<"s2=";
  4426. cin>>s2;
  4427. cout<<"s3=";
  4428. cin>>s3;
  4429. cout<<"s4=";
  4430. cin>>s4;
  4431. cout<<"s5=";
  4432. cin>>s5;
  4433. cout<<"s1="<<s1<<endl;
  4434. cout<<"s2="<<s2<<endl;
  4435. cout<<"s3="<<s3<<endl;
  4436. cout<<"s4="<<s4<<endl;
  4437. cout<<"s5="<<s5<<endl;
  4438. }
  4439. #include <iostream>
  4440. #include <string>
  4441. using namespace std;
  4442. //测试字符串(string)对象
  4443. void main()
  4444. {
  4445. //创建string对象
  4446. string s1,s2;
  4447. //string对象的赋值运算
  4448. s1="One";
  4449. s2="Two";
  4450. cout<<"s1="<<s1<<endl;
  4451. cout<<"s2="<<s2<<endl;
  4452. //string对象的连接运算
  4453. string s3;
  4454. s3=s1+" and "+s2;
  4455. cout<<"s3="<<s3<<endl;
  4456. //组合赋值连接运算
  4457. s3+=" and Three";
  4458. cout<<"s3="<<s3<<endl;
  4459. //比较运算及其结果显示
  4460. for (int i=1;i<=3;i++) {
  4461. cout<<"---------------------"<<endl;
  4462. cout<<"s1=";
  4463. cin>>s1;
  4464. cout<<"s2=";
  4465. cin>>s2;
  4466. if (s1<s2) //小于
  4467. cout<<s1<<" < "<<s2<<endl;
  4468. if (s1<=s2) //小于等于
  4469. cout<<s1<<" <= "<<s2<<endl;
  4470. if (s1==s2) //等于
  4471. cout<<s1<<" == "<<s2<<endl;
  4472. if (s1>s2) //大于
  4473. cout<<s1<<" > "<<s2<<endl;
  4474. if (s1>=s2) //大于等于
  4475. cout<<s1<<" >= "<<s2<<endl;
  4476. if (s1!=s2) //不等
  4477. cout<<s1<<" != "<<s2<<endl;
  4478. }
  4479. }
  4480. #include <iostream>
  4481. #include <string>
  4482. using namespace std;
  4483. //测试字符串(string)对象
  4484. void main()
  4485. {
  4486. //创建string对象,并显示
  4487. string s1="This";
  4488. string s2="book.";
  4489. cout<<"s1: "<<s1<<endl;
  4490. cout<<"s2: "<<s2<<endl;
  4491. //使用length成员函数
  4492. cout<<"s1.length()="<<s1.length()<<endl;
  4493. cout<<"s2.length()="<<s2.length()<<endl;
  4494. //使用append成员函数
  4495. s1.append(s2);
  4496. cout<<"s1: "<<s1<<endl;
  4497. //使用find成员函数和下标运算
  4498. int pos=s1.find('b');
  4499. cout<<"s1["<<pos<<"]="<<s1[pos]<<endl;
  4500. //使用insert成员函数
  4501. s1.insert(pos," is a ");
  4502. cout<<s1<<endl;
  4503. //使用assign成员函数
  4504. s1.assign("Good");
  4505. cout<<s1<<endl;
  4506. }
  4507. //根据半径计算圆的周长和面积
  4508. #include <iostream.h>
  4509. const float PI=3.1416; //声明常量(只读变量)PI为3.1416
  4510. float fCir_L(float); //声明自定义函数fCir_L()的原型
  4511. float fCir_S(float); //声明自定义函数fCir_S()的原型
  4512. //以下是main()函数
  4513. main()
  4514. {
  4515. float r,l,s; //声明3个变量
  4516. cout<<"R="; //显示字符串
  4517. cin>>r; //键盘输入
  4518. l=fCir_L(r); //计算圆的周长,赋值给变量l
  4519. s=fCir_S(r); //计算圆的面积,赋值给变量s
  4520. cout<<"l="<<l; //显示计算结果
  4521. cout<<"\ns="<<s;
  4522. }
  4523. //定义计算圆的周长的函数fCir_L()
  4524. float fCir_L(float x)
  4525. {
  4526. float z=-1.0; //声明局部变量
  4527. if (x>=0.0) //如果参数大于0,则计算圆的周长
  4528. z=2*PI*x;
  4529. return(z); //返回函数值
  4530. }
  4531. //定义计算圆的面积的函数fCir_S()
  4532. float fCir_S(float x)
  4533. {
  4534. float z=-1.0; //声明局部变量
  4535. if (x>=0.0) //如果参数大于0,则计算圆的面积
  4536. z=PI*x*x;
  4537. return(z); //返回函数值
  4538. }
  4539. #include<iostream.h>
  4540. #include<stdlib.h>
  4541. #define MAX 30
  4542. //main()的定义
  4543. int main(void)
  4544. {
  4545. char str[MAX],*p;
  4546. //从键盘上输入int数
  4547. cout<<"Please input a int:"<<endl;
  4548. int n;
  4549. cin>>n;
  4550. //将整型数n按十进制转换为字符串并输出
  4551. p=itoa(n,str,10);
  4552. cout<<"str="<<str<<endl;
  4553. cout<<"p="<<p<<endl;
  4554. //将整型数n按十六进制转换为字符串并输出
  4555. p=itoa(n,str,16);
  4556. cout<<"str="<<str<<endl;
  4557. cout<<"p="<<p<<endl;
  4558. //从键盘上输入double类型的数据
  4559. cout<<"Please input a double:"<<endl;
  4560. double x;
  4561. cout<<"x=";
  4562. cin>>x;
  4563. //将浮点数x转换为字符串后输出
  4564. p=gcvt(x,10,str);
  4565. cout<<"str="<<str<<endl;
  4566. cout<<"p="<<p<<endl;
  4567. return 0;
  4568. }
  4569. #include<iostream.h>
  4570. #include<stdlib.h>
  4571. #define MAX 30
  4572. //main()的定义
  4573. int main(void)
  4574. {
  4575. char str[MAX];
  4576. //字符串转换为int和long类型数据
  4577. cout<<"Please input a string:"<<endl;
  4578. cin>>str;
  4579. int n=atoi(str);
  4580. cout<<"n="<<n<<endl;
  4581. long l=atol(str);
  4582. cout<<"l="<<l<<endl;
  4583. //字符串转换为double类型
  4584. cout<<"Please input a string:"<<endl;
  4585. cin>>str;
  4586. double x=atof(str);
  4587. cout<<"x="<<x<<endl;
  4588. return 0;
  4589. }
  4590. #include<iostream.h>
  4591. #include <stdlib.h>
  4592. #include <time.h>
  4593. //定义产生[n1,n2]范围int随机数的函数
  4594. int rand(int n1,int n2) {
  4595. if (n1>n2) return -1;
  4596. if (n1==n2) return 0;
  4597. int temp=n1+int((n2-n1)*double(rand())/RAND_MAX);
  4598. return temp;
  4599. }
  4600. //main()函数的定义,加法练习程序
  4601. void main( void )
  4602. {
  4603. int i;
  4604. //使用当前的系统时间初始化随机数种子
  4605. srand( (unsigned)time( NULL ) );
  4606. //加法练习
  4607. int a,b,c;
  4608. do {
  4609. a=rand(0,20);
  4610. b=rand(0,20);
  4611. L1: cout<<a<<"+"<<b<<"=";
  4612. cin>>c;
  4613. if (c==0) break;
  4614. if (c!=a+b) {
  4615. cout<<"Error! Try again!"<<endl;
  4616. goto L1;
  4617. }
  4618. cout<<"OK!"<<endl;
  4619. } while (1);
  4620. }
  4621. #include<iostream.h>
  4622. #include <stdlib.h>
  4623. #include <math.h>
  4624. #define PI 3.1415926535
  4625. //main()函数的定义
  4626. void main( void )
  4627. {
  4628. int i;
  4629. double x=PI/180;
  4630. cout<<"X\tSIN(X)\t\tCOS(X)"<<endl;
  4631. cout<<"---------------------------------------"<<endl;
  4632. for (i=0;i<=360;i=i+30) {
  4633. cout<<i<<"\t";
  4634. cout.precision(2);
  4635. cout<<sin(i*x)<<"\t\t";
  4636. cout<<cos(i*x)<<endl;
  4637. }
  4638. }
  4639. #include<iostream.h>
  4640. #include <stdlib.h>
  4641. #include <math.h>
  4642. #define PI 3.1415926535
  4643. //main()函数的定义
  4644. void main( void )
  4645. {
  4646. int i;
  4647. double d=180/PI;
  4648. cout<<"X\tASIN(X)\t\tACOS(X)"<<endl;
  4649. cout<<"---------------------------------------"<<endl;
  4650. for (double x=0;x<=1.0+0.05;x=x+0.1) {
  4651. cout<<x<<"\t";
  4652. cout<<int(asin(x)*d)<<"\t\t";
  4653. cout<<int(acos(x)*d)<<endl;
  4654. }
  4655. }
  4656. #include<iostream.h>
  4657. #include <stdlib.h>
  4658. #include <math.h>
  4659. //main()函数的定义
  4660. void main( void )
  4661. {
  4662. _complex a={3,4},b={3,-4};
  4663. double d=cabs(a);
  4664. cout<<"cabs("<<a.x<<","<<a.y<<")="<<d<<endl;
  4665. cout<<"cabs("<<b.x<<","<<b.y<<")="<<cabs(b)<<endl;
  4666. }
  4667. ##include<iostream.h>
  4668. #include <stdlib.h>
  4669. #include <math.h>
  4670. //main()函数的定义
  4671. void main( void )
  4672. {
  4673. double x;
  4674. //循环输入数据计算对数
  4675. do {
  4676. cout<<"x=";
  4677. cin>>x;
  4678. if (x<=0) break;
  4679. cout<<"log("<<x<<")="<<log(x)<<endl;
  4680. cout<<"log10("<<x<<")="<<log10(x)<<endl;
  4681. } while(1);
  4682. }
  4683. #include<iostream.h>
  4684. #include <stdlib.h>
  4685. #include <math.h>
  4686. //main()函数的定义
  4687. void main( void )
  4688. {
  4689. double y;
  4690. for(double x=-5;x<=5;x++){
  4691. y=exp(x);
  4692. cout<<"exp("<<x<<")="<<y<<endl;
  4693. }
  4694. }
  4695. #include<iostream.h>
  4696. #include <stdlib.h>
  4697. #include <math.h>
  4698. //main()函数的定义
  4699. void main( void )
  4700. {
  4701. double y;
  4702. int N;
  4703. //输入一个大于等于0的数
  4704. do {
  4705. cout<<"N=";
  4706. cin>>N;
  4707. if (N>=0) break;
  4708. } while (1);
  4709. //计算并显示
  4710. for(int i=0;i<=N;i++){
  4711. y=pow(2,i);
  4712. cout<<"pow("<<2<<","<<i<<")="<<y<<endl;
  4713. }
  4714. }
  4715. #include<iostream.h>
  4716. #include <stdlib.h>
  4717. #include <math.h>
  4718. //main()函数的定义
  4719. void main( void )
  4720. {
  4721. double y;
  4722. for(int i=0;i<=10;i++){
  4723. y=sqrt(i);
  4724. cout<<"sqrt("<<i<<")="<<y<<endl;
  4725. }
  4726. }
  4727. #include<iostream.h>
  4728. #include <time.h>
  4729. //时间延迟函数
  4730. void Dtime(int dt) {
  4731. time_t current_time;
  4732. time_t start_time;
  4733. // 得到开始时间
  4734. time(&start_time);
  4735. do
  4736. {
  4737. time(¤t_time);
  4738. }
  4739. while ((current_time - start_time) < dt);
  4740. }
  4741. //main()函数的定义
  4742. void main(void)
  4743. {
  4744. cout<<"The First information!"<<endl;
  4745. cout<<"About to delay 5 seconds"<<endl;
  4746. Dtime(5);
  4747. cout<<"The Second information!"<<endl;
  4748. }
  4749. #include<iostream.h>
  4750. #include <time.h>
  4751. //main()函数的定义
  4752. void main(void)
  4753. {
  4754. //声明time_t类型的变量,其以秒为单位存放系统时间
  4755. time_t current_time;
  4756. //得到当前的系统时间(秒)
  4757. time(¤t_time);
  4758. //转换系统时间为tm结构的时间信息
  4759. tm *ptime=gmtime(¤t_time);
  4760. //显示time_t结构的时间
  4761. cout<<"current_time:"<<current_time<<endl;
  4762. //显示tm结构的时间信息
  4763. cout<<"seconds after the minute:"<<(ptime->tm_sec)<<endl;
  4764. cout<<"minutes after the hour:"<<(ptime->tm_min)<<endl;
  4765. cout<<"hours since midnight:"<<(ptime->tm_hour)<<endl;
  4766. cout<<"day of the month:"<<(ptime->tm_mday)<<endl;
  4767. cout<<"months since January:"<<(ptime->tm_mon)<<endl;
  4768. cout<<"years since 1900:"<<(ptime->tm_year)<<endl;
  4769. cout<<"days since Sunday:"<<(ptime->tm_wday)<<endl;
  4770. cout<<"days since January 1:"<<(ptime->tm_yday)<<endl;
  4771. cout<<"daylight savings time flag:"<<(ptime->tm_isdst)<<endl;
  4772. }
  4773. #include<iostream.h>
  4774. #include <time.h>
  4775. //main()函数的定义
  4776. void main(void)
  4777. {
  4778. //声明变量
  4779. time_t current_time;
  4780. //得到当前系统时间
  4781. time(¤t_time);
  4782. //转换系统时间为tm结构
  4783. tm *ptime=gmtime(¤t_time);
  4784. //转换time_t类型的时间字符串并显示
  4785. char *timep=ctime(¤t_time);
  4786. cout<<"ctime(¤t_time):"<<endl;
  4787. cout<<timep;
  4788. //转换tm类型的数据转换为时间字符串并显示
  4789. char *tmp=asctime(ptime);
  4790. cout<<"asctime(ptime):"<<endl;
  4791. cout<<timep;
  4792. }
  4793. #include<iostream.h>
  4794. #include<conio.h>
  4795. #include <time.h>
  4796. //定义时间延迟函数
  4797. void Dtime(double dt) {
  4798. time_t current_time;
  4799. time_t start_time;
  4800. //得到开始时间
  4801. time(&start_time);
  4802. //延迟处理
  4803. do
  4804. {
  4805. time(¤t_time);
  4806. }
  4807. while (difftime(current_time,start_time)<dt);
  4808. }
  4809. //main()函数的定义
  4810. void main(void)
  4811. {
  4812. //声明变量
  4813. int i;
  4814. time_t current_time;
  4815. char *timep;
  4816. //循环10次,每隔2秒显示一次时间
  4817. for(i=0;i<10;i++) {
  4818. time(¤t_time);
  4819. timep=ctime(¤t_time);
  4820. cputs(timep);
  4821. Dtime(2);
  4822. }
  4823. }
  4824. #include<iostream.h>
  4825. #include<stdlib.h>
  4826. #include<malloc.h>
  4827. int main(void)
  4828. {
  4829. //定义结构类型
  4830. struct student {
  4831. int num;
  4832. char name[20];
  4833. float grade;
  4834. };
  4835. //声明结构指针变量
  4836. struct student *sp;
  4837. //计算申请的内存量
  4838. int size=sizeof(struct student);
  4839. //申请需要的存储空间并强制类型转换
  4840. sp=(struct student*)malloc(size);
  4841. //为结构对象输入数据
  4842. cout<<"nmu:";
  4843. cin>>(sp->num);
  4844. cout<<"name:";
  4845. cin>>(sp->name);
  4846. cout<<"grade:";
  4847. cin>>(sp->grade);
  4848. //输出结构对象的数据
  4849. cout<<"num:"<<(sp->num)<<endl;
  4850. cout<<"name:"<<(sp->name)<<endl;
  4851. cout<<"grade:"<<(sp->grade);
  4852. //释放内存
  4853. free(sp);
  4854. }
  4855. #include<iostream.h>
  4856. #include<conio.h>
  4857. #include <time.h>
  4858. //定义时间延迟函数
  4859. void Dtime(double dt) {
  4860. time_t current_time;
  4861. time_t start_time;
  4862. // 得到开始时间
  4863. time(&start_time);
  4864. //延迟处理
  4865. do
  4866. {
  4867. time(¤t_time);
  4868. }
  4869. while (difftime(current_time,start_time)<dt);
  4870. }
  4871. //控制台函数显示
  4872. void cputs_show(int n) {
  4873. time_t current_time;
  4874. char *timep;
  4875. cputs("Show time with cputs\n");
  4876. for(int i=0;i<5;i++) {
  4877. time(¤t_time);
  4878. timep=ctime(¤t_time);
  4879. cputs(timep);
  4880. Dtime(n);
  4881. }
  4882. }
  4883. //cout对象显示
  4884. void cout_show(int n) {
  4885. time_t current_time;
  4886. char *timep;
  4887. cout<<"Show time with cout"<<endl;
  4888. for(int i=0;i<5;i++) {
  4889. time(¤t_time);
  4890. timep=ctime(¤t_time);
  4891. cout<<timep;
  4892. Dtime(n);
  4893. }
  4894. }
  4895. //main()函数的定义
  4896. void main(void)
  4897. {
  4898. cputs_show(1);
  4899. cout_show(1);
  4900. }
  4901. #include<stdio.h>
  4902. main()
  4903. {
  4904. //输出字符串
  4905. printf("He said \"Hello!\"");
  4906. //输出各进制整数
  4907. int i=64;
  4908. printf("\ni=%d",i); //以十进制格式输出
  4909. printf("\ni=%o",i); //以八进制格式输出
  4910. printf("\ni=%x",i); //以十六进制格式输出
  4911. printf("\ni=%d,%o,%x",i,i,i); //各种格式混合输出
  4912. //输出浮点数
  4913. float x=3141.5926;
  4914. printf("\nx=%f",x); //指定输出浮点数的格式为十进制形式
  4915. printf("\nx=%e",x); //指定输出浮点数的格式为指数形式
  4916. //控制输出项宽度
  4917. int j=123;
  4918. printf("\nj=%-10d",j); //任选项"-"指定左对齐,W 指定宽度为10
  4919. printf("\nj=%10d\n",j); //W 指定宽度为10
  4920. //控制输出精度
  4921. float y=3.1415926;
  4922. printf("y=%10.2f\n",y); //W 指定宽度为10,P指定小数点后保留2位
  4923. printf("y=%10.5f\n",y); //W 指定宽度为10,P指定小数点后保留5位
  4924. }
  4925. #include<stdio.h>
  4926. main()
  4927. {
  4928. //输入字符串
  4929. char str[80];
  4930. printf("str:"); //显示提示
  4931. scanf("%s",str);
  4932. printf("The string:%s",str);
  4933. //输入各进制整数
  4934. int a,b,c,sum;
  4935. printf("\na\tb\tc\n"); //显示提示
  4936. scanf("%d %o %x",&a,&b,&c); //以十进制、八进制、十六进制形式输入数据
  4937. sum=a+b+c;
  4938. printf("a=%d b=%d c=%d sum=%d",a,b,c,sum);
  4939. //输入浮点数并计算显示
  4940. float x,y; //声明变量
  4941. printf("\nx\ty\n"); //显示提示
  4942. scanf("%f %f",&x,&y); //对非空白字符"x= y="读入,不保存
  4943. printf("sum=%f product=%f\n",x+y, x*y); //显示表达式的值
  4944. }
  4945. #include<iostream.h>
  4946. #include<direct.h>
  4947. #include<errno.h>
  4948. #define MAX_PATH 250
  4949. main()
  4950. {
  4951. //声明变量
  4952. char *p,str[MAX_PATH];
  4953. //设置新目录
  4954. if (mkdir("d:\\ABC")){
  4955. cout<<"mkdir Error!"<<endl;
  4956. }
  4957. //更该工作目录
  4958. if (chdir("d:\\ABC")){
  4959. cout<<"chdir Error!"<<endl;
  4960. }
  4961. //读取当前目录
  4962. if ((p=getcwd(str,MAX_PATH))==NULL) {
  4963. cout<<"getcwd Error!"<<endl;
  4964. }
  4965. else
  4966. {
  4967. cout<<"p:"<<p<<endl;
  4968. cout<<"str:"<<str<<endl;
  4969. }
  4970. //更该工作目录
  4971. if (chdir("d:\\")){
  4972. cout<<"chdir Error!"<<endl;
  4973. }
  4974. //删除指定目录
  4975. if (rmdir("d:\\ABC")==-1)
  4976. cout<<"rmdir Error!"<<endl;
  4977. }
  4978. #include<iostream.h>
  4979. #include <time.h>
  4980. #include <sys/types.h>
  4981. #include <sys/stat.h>
  4982. #include <stdio.h>
  4983. void main( void )
  4984. {
  4985. struct stat buf;
  4986. int result;
  4987. //获得c:\Windows\Calc.exe文件的状态信息
  4988. result =stat( "c:\\windows\\Calc.exe", &buf );
  4989. //显示Calc.exe文件的状态信息
  4990. if( result != 0 )
  4991. perror( "Problem getting information" );
  4992. else
  4993. {
  4994. cout<<"Size of the file in bytes:"<<buf.st_size<<endl;
  4995. cout<<"Drive number of the disk containing the file :";
  4996. cout<<char(buf.st_dev + 'A')<<endl;
  4997. cout<<"Time of creation of the file:"<<ctime(&buf.st_ctime);
  4998. cout<<"Time of last access of the file:"<<ctime(&buf.st_atime);
  4999. cout<<"Time of last modification of the file:"<<ctime(&buf.st_mtime);
  5000. }
  5001. }
  5002. #include<iostream.h>
  5003. #include <string.h>
  5004. void main( void )
  5005. {
  5006. //设置字符串
  5007. char string[] = "Fill the string with something";
  5008. cout<<"string:"<<string<<endl;
  5009. char *p=strset(string,'*');
  5010. cout<<"p :"<<p<<endl;
  5011. cout<<"string:"<<string<<endl;
  5012. //按指定字符和指定数目设置字符数组
  5013. char string1[] = "Fill the string with something";
  5014. cout<<"string1:"<<string1<<endl;
  5015. p=strnset(string1,'*',5);
  5016. cout<<"p :"<<p<<endl;
  5017. cout<<"string1:"<<string1<<endl;
  5018. }
  5019. #include<iostream.h>
  5020. #include <string.h>
  5021. void main( void )
  5022. {
  5023. //拷贝字符串常量到字符数组
  5024. char string[80] = "Fill the string with something";
  5025. cout<<"string:"<<string<<endl;
  5026. cout<<"strcpy:"<<endl;
  5027. char *p=strcpy(string,"abc");
  5028. cout<<"p :"<<p<<endl;
  5029. cout<<"string:"<<string<<endl;
  5030. char str[80];
  5031. cout<<"str:";
  5032. cin>>str;
  5033. p=strcpy(string,str);
  5034. cout<<"p :"<<p<<endl;
  5035. cout<<"string:"<<string<<endl;
  5036. //拷贝前5个字符到string中
  5037. cout<<"str:";
  5038. cin>>str;
  5039. cout<<"strncpy:"<<endl;
  5040. p=strncpy(string,str,strlen(str));
  5041. cout<<"p :"<<p<<endl;
  5042. cout<<"string:"<<string<<endl;
  5043. }
  5044. #include<iostream.h>
  5045. #include <string.h>
  5046. void main( void )
  5047. {
  5048. //声明字符数组和字符型指针变量
  5049. char string[80],*p;
  5050. //拷贝字符串
  5051. strcpy( string, "I'll see you");
  5052. cout<<"string:"<<string<<endl;
  5053. //追加字符串
  5054. p=strcat( string, " in the morning.");
  5055. cout<<"String: "<<string<<endl;
  5056. cout<<"p : "<<p<<endl;
  5057. }
  5058. #include<iostream.h>
  5059. #include <string.h>
  5060. //字符串输入函数
  5061. void str_input(char *p1,char *p2)
  5062. {
  5063. cout<<"string1:";
  5064. cin>>p1;
  5065. cout<<"string2:";
  5066. cin>>p2;
  5067. }
  5068. //显示strcmp()函数的比较结果
  5069. void strcmp_put(char *p1,char *p2)
  5070. {
  5071. cout<<"strcmp():"<<endl;
  5072. int result=strcmp(p1,p2);
  5073. if (result>0)
  5074. cout<<p1<<" greater than "<<p2<<endl;
  5075. if (result<0)
  5076. cout<<p1<<" less than "<<p2<<endl;
  5077. if (result==0)
  5078. cout<<p1<<" identical to "<<p2<<endl;
  5079. }
  5080. //显示stricmp()函数的比较结果
  5081. void stricmp_put(char *p1,char *p2)
  5082. {
  5083. cout<<"stricmp():"<<endl;
  5084. int result=stricmp(p1,p2);
  5085. if (result>0)
  5086. cout<<p1<<" greater than "<<p2<<endl;
  5087. if (result<0)
  5088. cout<<p1<<" less than "<<p2<<endl;
  5089. if (result==0)
  5090. cout<<p1<<" identical to "<<p2<<endl;
  5091. }
  5092. //显示strncmp()函数的比较结果
  5093. void strncmp_put(char *p1,char *p2,size_t count )
  5094. {
  5095. cout<<"strncmp():"<<endl;
  5096. int result=strncmp(p1,p2,count);
  5097. if (result>0)
  5098. cout<<p1<<" greater than "<<p2<<endl;
  5099. if (result<0)
  5100. cout<<p1<<" less than "<<p2<<endl;
  5101. if (result==0)
  5102. cout<<p1<<" identical to "<<p2<<endl;
  5103. }
  5104. //main()函数
  5105. void main( void )
  5106. {
  5107. //声明字符数组
  5108. char str1[80],str2[80],p;
  5109. int i;
  5110. //测试测试各字符串比较函数
  5111. for(i=1;i<=3;i++) {
  5112. str_input(str1,str2);
  5113. strcmp_put(str1,str2);
  5114. stricmp_put(str1,str2);
  5115. strncmp_put(str1,str2,3);
  5116. cout<<"----------------------"<<endl;
  5117. }
  5118. }
  5119. #include<iostream.h>
  5120. #include <string.h>
  5121. //main()函数
  5122. void main( void )
  5123. {
  5124. //声明字符数组
  5125. char string[80],*p;
  5126. int i;
  5127. //转换字符串中的小写字母为大写
  5128. cout<<"Convert a string to uppercase:"<<endl;
  5129. cout<<"string:";
  5130. cin>>string;
  5131. p=strupr(string);
  5132. cout<<"p:"<<p<<endl;
  5133. cout<<"string:"<<string<<endl;
  5134. cout<<"----------------------"<<endl;
  5135. //转换字符串中的大写字母为小写
  5136. cout<<"Convert a string to lowercase:"<<endl;
  5137. cout<<"string:";
  5138. cin>>string;
  5139. p=strlwr(string);
  5140. cout<<"p:"<<p<<endl;
  5141. cout<<"string:"<<string<<endl;
  5142. }
  5143. #include<iostream.h>
  5144. #include <string.h>
  5145. //main()函数
  5146. void main( void )
  5147. {
  5148. //声明字符数组
  5149. char string[]="This is a test.";
  5150. int n;
  5151. //获得字符串的长度
  5152. cout<<"string:"<<string<<endl;
  5153. n=strlen(string);
  5154. cout<<"The length of "<<"\""<<string<<"\": "<<n<<endl;
  5155. //输入字符并计算其长度
  5156. cout<<"string:";
  5157. cin>>string;
  5158. n=strlen(string);
  5159. cout<<"The length of "<<"\""<<string<<"\": "<<n<<endl;
  5160. }
  5161. #include<iostream.h>
  5162. #include <string.h>
  5163. //main()函数
  5164. void main( void )
  5165. {
  5166. //声明字符数组
  5167. char ch,string[80],*p;
  5168. int n;
  5169. //输入字符串和要查找的字符
  5170. cout<<"Test strchr():"<<endl;
  5171. cout<<"string:";
  5172. cin>>string;
  5173. cout<<"ch :";
  5174. cin>>ch;
  5175. //在string中查找ch中的字符并显示
  5176. p=strchr(string,ch);
  5177. cout<<"p :"<<p<<endl;
  5178. //输入字符串和要查找的字符串并查找
  5179. char substr[80];
  5180. cout<<"Test strstr():"<<endl;
  5181. cout<<"substr:";
  5182. cin>>substr;
  5183. //在string中查找substr中的字符串并显示
  5184. p=strstr(string,substr);
  5185. cout<<"p :"<<p<<endl;
  5186. }
  5187. #include<iostream.h>
  5188. #include <string.h>
  5189. //main()函数
  5190. void main( void )
  5191. {
  5192. //声明字符数组
  5193. char string[80],*p;
  5194. //输入字符串并将其反转
  5195. cout<<"string:";
  5196. cin>>string;
  5197. p=strrev(string );
  5198. cout<<"p :"<<p<<endl;
  5199. cout<<"string:"<<string<<endl;
  5200. }
  5201. #include<iostream.h>
  5202. #include <string.h>
  5203. char string[80];
  5204. char seps[] = " ,\t\n";
  5205. char *token;
  5206. void main( void )
  5207. {
  5208. //从键盘上输入两个语句
  5209. for (int i=1;i<3;i++) {
  5210. cout<<"Please input a sentence:"<<endl;
  5211. //整行输入
  5212. cin.getline(string,80);
  5213. cout<<"Tokens:"<<endl;
  5214. //首次分离字符串
  5215. token = strtok( string, seps );
  5216. while( token != NULL ) //结束分离判断
  5217. {
  5218. cout<<token<<endl;
  5219. //下次分离字符串
  5220. token = strtok( NULL, seps );
  5221. }
  5222. }
  5223. }
  5224. #include<iostream.h>
  5225. #include<stdio.h>
  5226. #include <string.h>
  5227. //main()函数
  5228. void main( void )
  5229. {
  5230. //声明变量和数组
  5231. char buffer[200], s[] = "computer", c = 'l';
  5232. int i = 35, j;
  5233. float fp = 1.7320534f;
  5234. //格式化输出到buffer
  5235. j = sprintf( buffer, "\tString: %s\n", s );
  5236. j += sprintf( buffer + j, "\tCharacter: %c\n", c );
  5237. j += sprintf( buffer + j, "\tInteger: %d\n", i );
  5238. j += sprintf( buffer + j, "\tReal: %f\n", fp );
  5239. cout<<"Output:"<<endl;
  5240. cout<<buffer;
  5241. cout<<"character count ="<<j<<endl;
  5242. }
  5243. //根据半径计算圆的周长和面积
  5244. #include <iostream.h>
  5245. const float PI=3.1416; //声明常量(只读变量)PI为3.1416
  5246. float fCir_L(float); //声明自定义函数fCir_L()的原型
  5247. float fCir_S(float); //声明自定义函数fCir_S()的原型
  5248. //以下是main()函数
  5249. main()
  5250. {
  5251. float r,l,s; //声明3个变量
  5252. cout<<"R="; //显示字符串
  5253. cin>>r; //键盘输入
  5254. l=fCir_L(r); //计算圆的周长,赋值给变量l
  5255. s=fCir_S(r); //计算圆的面积,赋值给变量s
  5256. cout<<"l="<<l; //显示计算结果
  5257. cout<<"\ns="<<s;
  5258. }
  5259. //定义计算圆的周长的函数fCir_L()
  5260. float fCir_L(float x)
  5261. {
  5262. float z=-1.0; //声明局部变量
  5263. if (x>=0.0) //如果参数大于0,则计算圆的周长
  5264. z=2*PI*x;
  5265. return(z); //返回函数值
  5266. }
  5267. //定义计算圆的面积的函数fCir_S()
  5268. float fCir_S(float x)
  5269. {
  5270. float z=-1.0; //声明局部变量
  5271. if (x>=0.0) //如果参数大于0,则计算圆的面积
  5272. z=PI*x*x;
  5273. return(z); //返回函数值
  5274. }
  5275. #include<iostream.h>
  5276. //定义名为max_value的函数模板
  5277. template <class T> T max_value (T a,T b)
  5278. {
  5279. return ((a> b)? a: b);
  5280. }
  5281. //在main()函数中测试max_value函数模板
  5282. void main(void)
  5283. {
  5284. //double类型数据使用max_value模板函数
  5285. double x = 1.2, y = 2.1;
  5286. cout<<"x="<<x<<"\t";
  5287. cout<<"y="<<y<<endl;
  5288. double result=max_value(x,y);
  5289. cout<<"max_value(x,y)="<<result<<endl;
  5290. cout<<"max_value(2*3.0,2+3.0)="<<max_value(2*3.0,2+3.0)<<endl;
  5291. cout<<"------------------"<<endl;
  5292. //int类型数据使用max_value模板函数
  5293. int n= 1, m= 6;
  5294. cout<<"n="<<n<<"\t";
  5295. cout<<"m="<<m<<endl;
  5296. cout<<"max_value(n,m)="<<max_value(n,m)<<endl;
  5297. cout<<"------------------"<<endl;
  5298. //char类型数据使用max_value模板函数
  5299. char ch1='A',ch2='a';
  5300. cout<<"ch1="<<ch1<<"\t";
  5301. cout<<"ch2="<<ch2<<endl;
  5302. cout<<"max_value(ch1,ch2)="<<max_value(ch1,ch2)<<endl;
  5303. cout<<"------------------"<<endl;
  5304. //字符串数据使用max_value模板函数
  5305. char str1[]="abc",str2[]="ABC",*p;
  5306. p=max_value(str1,str2);
  5307. cout<<"max_value("<<str1<<","<<str2<<")="<<p<<endl;
  5308. }
  5309. #include<iostream.h>
  5310. //函数模板的原型
  5311. template <class T1, class T2> void display(T1 x, T2 y);
  5312. //在main()函数中测试display函数模板
  5313. void main(void)
  5314. {
  5315. //声明变量
  5316. char c='A';
  5317. char str[]="This is a test";
  5318. int n=10;
  5319. float x=1.5;
  5320. double z=3.1415926;
  5321. //两个参数类型相同
  5322. display(c, char(c+2));
  5323. display(str, str);
  5324. display(n, 2*n);
  5325. display(x,2*x);
  5326. display(z, 2*z);
  5327. cout<<"------------------"<<endl;
  5328. //两个参数类型不同
  5329. display(c, str);
  5330. display(str, c);
  5331. display(n, str);
  5332. display(str,2*x);
  5333. display(z, n);
  5334. }
  5335. //定义名为display的函数模板
  5336. template <class T1, class T2> void display(T1 x, T2 y)
  5337. {
  5338. cout << x << " " << y << endl;
  5339. }
  5340. #include<iostream.h>
  5341. //声明引用参数的函数模板原型
  5342. template <class T> void swap(T &x, T &y);
  5343. //定义一个结构类型
  5344. struct student {
  5345. int n;
  5346. char name[20];
  5347. float grade;
  5348. };
  5349. //在main()函数中测试swap()函数模板
  5350. void main(void)
  5351. {
  5352. //交换两个int型变量中的数据
  5353. int m=3,n=5;
  5354. cout<<"m="<<m<<" n="<<n<<endl;
  5355. swap(m,n);
  5356. cout<<"m="<<m<<" n="<<n<<endl;
  5357. cout<<"-------------------"<<endl;
  5358. //交换两个double型变量中的数据
  5359. double x=3.5,y=5.7;
  5360. cout<<"x="<<x<<" y="<<y<<endl;
  5361. swap(x,y);
  5362. cout<<"x="<<x<<" y="<<y<<endl;
  5363. cout<<"-------------------"<<endl;
  5364. //交换两个char型变量中的数据
  5365. char c1='A',c2='a';
  5366. cout<<"c1="<<c1<<" c2="<<c2<<endl;
  5367. swap(c1,c2);
  5368. cout<<"c1="<<c1<<" c2="<<c2<<endl;
  5369. cout<<"-------------------"<<endl;
  5370. //交换两个结构变量中的数据
  5371. student s1={1001,"ZhangHua",90};
  5372. student s2={1011,"LiWei",95.5};
  5373. cout<<"s1: ";
  5374. cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl;
  5375. cout<<"s2: ";
  5376. cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl;
  5377. swap(s1,s2);
  5378. cout<<"swap(s1,s2):"<<endl;
  5379. cout<<"s1: ";
  5380. cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl;
  5381. cout<<"s2: ";
  5382. cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl;
  5383. }
  5384. //定义名为swap的函数模板用于交换两个变量中的数据
  5385. template <class T> void swap(T &x, T &y)
  5386. {
  5387. T temp;
  5388. temp=x;
  5389. x=y;
  5390. y=temp;
  5391. }
  5392. #include<iostream.h>
  5393. //声明函数模板的原型语句
  5394. template <class T> void swap(T *x, T *y);
  5395. //定义一个结构类型
  5396. struct student {
  5397. int n;
  5398. char name[20];
  5399. float grade;
  5400. };
  5401. //在main()函数中测试swap()函数模板
  5402. void main(void)
  5403. {
  5404. //交换两个int型变量中的数据
  5405. int m=3,n=5;
  5406. cout<<"m="<<m<<" n="<<n<<endl;
  5407. swap(&m,&n);
  5408. cout<<"m="<<m<<" n="<<n<<endl;
  5409. cout<<"-------------------"<<endl;
  5410. //交换两个double型变量中的数据
  5411. double x=3.5,y=5.7;
  5412. cout<<"x="<<x<<" y="<<y<<endl;
  5413. swap(&x,&y);
  5414. cout<<"x="<<x<<" y="<<y<<endl;
  5415. cout<<"-------------------"<<endl;
  5416. //交换两个char型变量中的数据
  5417. char c1='A',c2='a';
  5418. cout<<"c1="<<c1<<" c2="<<c2<<endl;
  5419. swap(&c1,&c2);
  5420. cout<<"c1="<<c1<<" c2="<<c2<<endl;
  5421. cout<<"-------------------"<<endl;
  5422. //交换两个结构变量中的数据
  5423. student s1={1001,"ZhangHua",90};
  5424. student s2={1011,"LiWei",95.5};
  5425. cout<<"s1: ";
  5426. cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl;
  5427. cout<<"s2: ";
  5428. cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl;
  5429. swap(&s1,&s2);
  5430. cout<<"swap(s1,s2):"<<endl;
  5431. cout<<"s1: ";
  5432. cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl;
  5433. cout<<"s2: ";
  5434. cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl;
  5435. }
  5436. //定义名为swap的函数模板用于交换两个变量中的数据
  5437. template <class T> void swap(T *x, T *y)
  5438. {
  5439. T temp;
  5440. temp=*x;
  5441. *x=*y;
  5442. *y=temp;
  5443. }
  5444. #include<iostream.h>
  5445. //定义输入函数模板
  5446. template <class T> void input(char *str,T &x) {
  5447. cout<<str<<"=";
  5448. cin>>x;
  5449. }
  5450. //定义输出函数模板
  5451. template <class T> void output(char *str,T x) {
  5452. cout<<str<<"="<<x<<endl;
  5453. }
  5454. //在main()函数中测试输入输出函数模板
  5455. void main(void)
  5456. {
  5457. //输入输出int型数据
  5458. int a,b;
  5459. input("a",a);
  5460. output("a",a);
  5461. b=3*a;
  5462. output("3*a",b);
  5463. output("a+b",a+b);
  5464. cout<<"-------------------"<<endl;
  5465. //输入输出double型数据
  5466. double x,y;
  5467. input("x",x);
  5468. output("x",x);
  5469. y=2*x;
  5470. output("y",y);
  5471. cout<<"-------------------"<<endl;
  5472. //输入输出char型数据
  5473. char c1;
  5474. input("c1",c1);
  5475. output("c1+2",char(c1+2));
  5476. cout<<"-------------------"<<endl;
  5477. //输入输出字符串数据
  5478. char string[80];
  5479. input("string",string);
  5480. output("string",string);
  5481. }
  5482. #include<iostream.h>
  5483. #include<string.h>
  5484. //显示数组的函数模板
  5485. template <class T> void arr_put(T arr[],int size) {
  5486. for (int i=0 ;i<=size;i++)
  5487. cout<<arr[i]<<" ";
  5488. cout<<endl;
  5489. }
  5490. //选择排序数组的函数模板
  5491. template <class T> void sort(T arr[],int size) {
  5492. T temp;
  5493. int i,j;
  5494. for (i=0;i<size;i++)
  5495. for (j=i+1;j<=size;j++)
  5496. if (arr[i]<=arr[j])
  5497. {
  5498. temp=arr[i];
  5499. arr[i]=arr[j];
  5500. arr[j]=temp;
  5501. }
  5502. }
  5503. //在main()函数中测试数组排序的函数模板
  5504. void main(void)
  5505. {
  5506. //用排序函数模板处理int型数组
  5507. cout<<"int:"<<endl;
  5508. int a[]={1,5,2,7,9,0,10,-1};
  5509. arr_put(a,7);
  5510. sort(a,7);
  5511. arr_put(a,7);
  5512. //用排序函数模板处理double型数组
  5513. cout<<"double:"<<endl;
  5514. double x[]={1.2,2.1,1.414,1.732};
  5515. arr_put(x,3);
  5516. sort(x,3);
  5517. arr_put(x,3);
  5518. //用排序函数模板处理char类型数组
  5519. cout<<"char:"<<endl;
  5520. char str[80];
  5521. cout<<"str:";
  5522. cin>>str;
  5523. int size=strlen(str);
  5524. arr_put(str,size);
  5525. sort(str,size);
  5526. arr_put(str,size);
  5527. }
  5528. #include<iostream.h>
  5529. #include<string.h>
  5530. //显示数组的函数模板
  5531. template <class T> void arr_put(T arr[],int size) {
  5532. for (int i=0 ;i<size;i++)
  5533. cout<<arr[i]<<" ";
  5534. cout<<endl;
  5535. }
  5536. //选择法对数组排序的函数模板
  5537. template <class T> void sort(T arr[],int size) {
  5538. T temp;
  5539. int i,j;
  5540. for (i=0;i<size-1;i++)
  5541. for (j=i+1;j<size;j++)
  5542. if (arr[i]>arr[j])
  5543. {
  5544. temp=arr[i];
  5545. arr[i]=arr[j];
  5546. arr[j]=temp;
  5547. }
  5548. }
  5549. //二分查找法的函数模板
  5550. template <class T> int binary_search(T array[], T value, int size)
  5551. {
  5552. int found = 0;
  5553. int high = size, low = 0, mid;
  5554. mid = (high + low) / 2;
  5555. cout<<"Looking for "<<value<<endl;
  5556. while ((! found) && (high >= low))
  5557. {
  5558. if (value == array[mid])
  5559. found = 1;
  5560. else if (value < array[mid])
  5561. high = mid - 1;
  5562. else
  5563. low = mid + 1;
  5564. mid = (high + low) / 2;
  5565. }
  5566. return((found) ? mid: -1);
  5567. }
  5568. //main()函数中使用处理数组的函数模板
  5569. void main(void)
  5570. {
  5571. //处理int型数组
  5572. int array[10]={1,3,5,7,9,2,4,6,8,10};
  5573. //显示数组初值
  5574. arr_put(array,10);
  5575. //对数组排序并显示
  5576. sort(array,10);
  5577. arr_put(array,10);
  5578. //查找数组
  5579. cout<<"Result of search: "<<binary_search(array, 3, 10)<<endl;
  5580. cout<<"Result of search: "<<binary_search(array, 2, 10)<<endl;
  5581. cout<<"Result of search: "<<binary_search(array, 9, 10)<<endl;
  5582. cout<<"Result of search: "<<binary_search(array, 5, 10)<<endl;
  5583. cout<<"------------------------------"<<endl;
  5584. //处理字符串型数组
  5585. char ch1,str[]="happy";
  5586. int size=strlen(str);
  5587. //显示数组初值
  5588. arr_put(str,size);
  5589. //对数组排序并显示
  5590. sort(str,size);
  5591. arr_put(str,size);
  5592. //查找数组
  5593. cout<<"Input a char:";
  5594. cin>>ch1;
  5595. cout<<"Result of search: "<<binary_search(str, ch1, size)<<endl;
  5596. }
  5597. #include<iostream.h>
  5598. //定义名为ex_class的类模板
  5599. template <class T> class ex_class
  5600. {
  5601. T value;
  5602. public:
  5603. ex_class(T v) { value=v; }
  5604. void set_value(T v) { value=v; }
  5605. T get_value(void) {return value;}
  5606. };
  5607. //main()函数中测试ex_class类模板
  5608. void main(void)
  5609. {
  5610. //测试int类型数据
  5611. ex_class <int> a(5),b(10);
  5612. cout<<"a.value:"<<a.get_value()<<endl;
  5613. cout<<"b.value:"<<b.get_value()<<endl;
  5614. //测试char类型数据
  5615. ex_class <char> ch('A');
  5616. cout<<"ch.value:"<<ch.get_value()<<endl;
  5617. ch.set_value('a');
  5618. cout<<"ch.value:"<<ch.get_value()<<endl;
  5619. //测试double类型数据
  5620. ex_class <double> x(5.5);
  5621. cout<<"x.value:"<<x.get_value()<<endl;
  5622. x.set_value(7.5);
  5623. cout<<"x.value:"<<x.get_value()<<endl;
  5624. }
  5625. #include <iostream.h>
  5626. //定义栈的尺寸
  5627. const int SIZE = 100;
  5628. //定义处理栈的类模板接口
  5629. template <class T> class stack {
  5630. T stck[SIZE];
  5631. int tos;
  5632. public:
  5633. stack(void) {
  5634. tos = 0;
  5635. cout << "Stack Initialized." << endl;
  5636. }
  5637. ~stack(void) {
  5638. cout << "Stack Destroyed." << endl;
  5639. }
  5640. void push(T);
  5641. T pop(void);
  5642. };
  5643. //定义栈的成员函数
  5644. template <class T> void stack<T>::push(T i)
  5645. {
  5646. if(tos==SIZE)
  5647. {
  5648. cout << "Stack is full." << endl;
  5649. return;
  5650. }
  5651. stck[tos++] = i;
  5652. }
  5653. template <class T> T stack<T>::pop(void)
  5654. {
  5655. if(tos==0)
  5656. {
  5657. cout << "Stack underflow." << endl;
  5658. return 0;
  5659. }
  5660. return stck[--tos];
  5661. }
  5662. //main()函数中测试stack类模板
  5663. void main(void)
  5664. {
  5665. //处理int类型数据的栈
  5666. cout<<"stack<int> a :"<<endl;
  5667. stack<int> a;
  5668. a.push(1);
  5669. a.push(2);
  5670. cout << a.pop() << " ";
  5671. cout << a.pop() << endl;
  5672. //处理double类型数据的栈
  5673. cout<<"stack<double> b :"<<endl;
  5674. stack<double> b;
  5675. b.push(99.3);
  5676. b.push(-12.23);
  5677. cout << b.pop() << " ";
  5678. cout << b.pop() <<endl;
  5679. //处理char类型数据的栈
  5680. cout<<"stack<char> c :"<<endl;
  5681. stack<char> c;
  5682. for(int i=0; i<10; i++)
  5683. c.push((char) 'A' + i);
  5684. for(i=0; i<10; i++)
  5685. cout <<c.pop();
  5686. cout << endl;
  5687. }
  5688. #include<iostream.h>
  5689. //定义名为ex_class的类模板
  5690. template <class T1,class T2> class ex_class
  5691. {
  5692. T1 value1;
  5693. T2 value2;
  5694. public:
  5695. ex_class(T1 v1,T2 v2) {
  5696. value1=v1;
  5697. value2=v2;
  5698. }
  5699. void set_value(T1 v1,T2 v2) {
  5700. value1=v1;
  5701. value2=v2;
  5702. }
  5703. void put_value(void) {
  5704. cout<<"valu1="<<value1<<endl;
  5705. cout<<"valu2="<<value2<<endl;
  5706. }
  5707. };
  5708. //main()函数中测试ex_class类模板
  5709. void main(void)
  5710. {
  5711. //测试int和double类型数据
  5712. ex_class <int,double> a(5,1.5);
  5713. cout<<"ex_class <int,double> a:"<<endl;
  5714. a.put_value();
  5715. a.set_value(100,3.14);
  5716. a.put_value();
  5717. //测试double和int类型数据
  5718. ex_class <double,int> b(0.5,5);
  5719. cout<<"ex_class <double,int> b:"<<endl;
  5720. b.put_value();
  5721. b.set_value(1.732,100);
  5722. b.put_value();
  5723. //测试char和int类型数据
  5724. ex_class <char,int> c('a',5);
  5725. cout<<"ex_class <char,int> c:"<<endl;
  5726. c.put_value();
  5727. c.set_value('B',100);
  5728. c.put_value();
  5729. //测试int和int类型数据
  5730. ex_class <int,int> d(5,10);
  5731. cout<<"ex_class <int,int> d:"<<endl;
  5732. d.put_value();
  5733. d.set_value(100,200);
  5734. d.put_value();
  5735. }
  5736. #include <iostream>
  5737. #include <list>
  5738. #include <numeric>
  5739. #include <algorithm>
  5740. using namespace std;
  5741. //创建一个list容器的实例LISTINT
  5742. typedef list<int> LISTINT;
  5743. //创建一个list容器的实例LISTCHAR
  5744. typedef list<int> LISTCHAR;
  5745. void main(void)
  5746. {
  5747. //--------------------------
  5748. //用list容器处理整型数据
  5749. //--------------------------
  5750. //用LISTINT创建一个名为listOne的list对象
  5751. LISTINT listOne;
  5752. //声明i为迭代器
  5753. LISTINT::iterator i;
  5754. //从前面向listOne容器中添加数据
  5755. listOne.push_front (2);
  5756. listOne.push_front (1);
  5757. //从后面向listOne容器中添加数据
  5758. listOne.push_back (3);
  5759. listOne.push_back (4);
  5760. //从前向后显示listOne中的数据
  5761. cout<<"listOne.begin()--- listOne.end():"<<endl;
  5762. for (i = listOne.begin(); i != listOne.end(); ++i)
  5763. cout << *i << " ";
  5764. cout << endl;
  5765. //从后向后显示listOne中的数据
  5766. LISTINT::reverse_iterator ir;
  5767. cout<<"listOne.rbegin()---listOne.rend():"<<endl;
  5768. for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
  5769. cout << *ir << " ";
  5770. }
  5771. cout << endl;
  5772. //使用STL的accumulate(累加)算法
  5773. int result = accumulate(listOne.begin(), listOne.end(),0);
  5774. cout<<"Sum="<<result<<endl;
  5775. cout<<"------------------"<<endl;
  5776. //--------------------------
  5777. //用list容器处理字符型数据
  5778. //--------------------------
  5779. //用LISTCHAR创建一个名为listOne的list对象
  5780. LISTCHAR listTwo;
  5781. //声明i为迭代器
  5782. LISTCHAR::iterator j;
  5783. //从前面向listTwo容器中添加数据
  5784. listTwo.push_front ('A');
  5785. listTwo.push_front ('B');
  5786. //从后面向listTwo容器中添加数据
  5787. listTwo.push_back ('x');
  5788. listTwo.push_back ('y');
  5789. //从前向后显示listTwo中的数据
  5790. cout<<"listTwo.begin()---listTwo.end():"<<endl;
  5791. for (j = listTwo.begin(); j != listTwo.end(); ++j)
  5792. cout << char(*j) << " ";
  5793. cout << endl;
  5794. //使用STL的max_element算法求listTwo中的最大元素并显示
  5795. j=max_element(listTwo.begin(),listTwo.end());
  5796. cout << "The maximum element in listTwo is: "<<char(*j)<<endl;
  5797. }
  5798. #include <iostream>
  5799. #include <vector>
  5800. using namespace std;
  5801. typedef vector<int> INTVECTOR;
  5802. //测试vector容器的功能
  5803. void main(void)
  5804. {
  5805. //vec1对象初始为空
  5806. INTVECTOR vec1;
  5807. //vec2对象最初有10个值为6的元素
  5808. INTVECTOR vec2(10,6);
  5809. //vec3对象最初有3个值为6的元素
  5810. INTVECTOR vec3(vec2.begin(),vec2.begin()+3);
  5811. //声明一个名为i的双向迭代器
  5812. INTVECTOR::iterator i;
  5813. //从前向后显示vec1中的数据
  5814. cout<<"vec1.begin()--vec1.end():"<<endl;
  5815. for (i =vec1.begin(); i !=vec1.end(); ++i)
  5816. cout << *i << " ";
  5817. cout << endl;
  5818. //从前向后显示vec2中的数据
  5819. cout<<"vec2.begin()--vec2.end():"<<endl;
  5820. for (i =vec2.begin(); i !=vec2.end(); ++i)
  5821. cout << *i << " ";
  5822. cout << endl;
  5823. //从前向后显示vec3中的数据
  5824. cout<<"vec3.begin()--vec3.end():"<<endl;
  5825. for (i =vec3.begin(); i !=vec3.end(); ++i)
  5826. cout << *i << " ";
  5827. cout << endl;
  5828. //测试添加和插入成员函数
  5829. vec1.push_back(2);
  5830. vec1.push_back(4);
  5831. vec1.insert(vec1.begin()+1,5);
  5832. vec1.insert(vec1.begin()+1,vec3.begin(),vec3.end());
  5833. cout<<"push() and insert():" <<endl;
  5834. for (i =vec1.begin(); i !=vec1.end(); ++i)
  5835. cout << *i << " ";
  5836. cout << endl;
  5837. //测试赋值成员函数
  5838. vec2.assign(8,1);
  5839. cout<<"vec2.assign(8,1):" <<endl;
  5840. for (i =vec2.begin(); i !=vec2.end(); ++i)
  5841. cout << *i << " ";
  5842. cout << endl;
  5843. //测试引用类函数
  5844. cout<<"vec1.front()="<<vec1.front()<<endl;
  5845. cout<<"vec1.back()="<<vec1.back()<<endl;
  5846. cout<<"vec1.at(4)="<<vec1.at(4)<<endl;
  5847. cout<<"vec1[4]="<<vec1[4]<<endl;
  5848. //测试移出和删除
  5849. vec1.pop_back();
  5850. vec1.erase(vec1.begin()+1,vec1.end()-2);
  5851. cout<<"vec1.pop_back() and vec1.erase():" <<endl;
  5852. for (i =vec1.begin(); i !=vec1.end(); ++i)
  5853. cout << *i << " ";
  5854. cout << endl;
  5855. //显示序列的状态信息
  5856. cout<<"vec1.capacity(): "<<vec1.capacity()<<endl;
  5857. cout<<"vec1.max_size(): "<<vec1.max_size()<<endl;
  5858. cout<<"vec1.size(): "<<vec1.size()<<endl;
  5859. cout<<"vec1.empty(): "<<vec1.empty()<<endl;
  5860. //vector序列容器的运算
  5861. cout<<"vec1==vec3: "<<(vec1==vec3)<<endl;
  5862. cout<<"vec1<=vec3: "<<(vec1<=vec3)<<endl;
  5863. }
  5864. #include <iostream>
  5865. #include <deque>
  5866. using namespace std;
  5867. typedef deque<int> INTDEQUE;
  5868. //从前向后显示deque队列的全部元素
  5869. void put_deque(INTDEQUE deque, char *name)
  5870. {
  5871. INTDEQUE::iterator pdeque;
  5872. cout << "The contents of " << name << " : ";
  5873. for(pdeque = deque.begin(); pdeque != deque.end(); pdeque++)
  5874. cout << *pdeque << " ";
  5875. cout<<endl;
  5876. }
  5877. //测试deqtor容器的功能
  5878. void main(void)
  5879. {
  5880. //deq1对象初始为空
  5881. INTDEQUE deq1;
  5882. //deq2对象最初有10个值为6的元素
  5883. INTDEQUE deq2(10,6);
  5884. //deq3对象最初有3个值为6的元素
  5885. INTDEQUE deq3(deq2.begin(),deq2.begin()+3);
  5886. //声明一个名为i的双向迭代器变量
  5887. INTDEQUE::iterator i;
  5888. //从前向后显示deq1中的数据
  5889. put_deque(deq1,"deq1");
  5890. //从前向后显示deq2中的数据
  5891. put_deque(deq2,"deq2");
  5892. //从前向后显示deq3中的数据
  5893. put_deque(deq3,"deq3");
  5894. //从deq1序列后面添加两个元素
  5895. deq1.push_back(2);
  5896. deq1.push_back(4);
  5897. cout<<"deq1.push_back(2) and deq1.push_back(4):"<<endl;
  5898. put_deque(deq1,"deq1");
  5899. //从deq1序列前面添加两个元素
  5900. deq1.push_front(5);
  5901. deq1.push_front(7);
  5902. cout<<"deq1.push_front(5) and deq1.push_front(7):"<<endl;
  5903. put_deque(deq1,"deq1");
  5904. //在deq1序列中间插入数据
  5905. deq1.insert(deq1.begin()+1,3,9);
  5906. cout<<"deq1.insert(deq1.begin()+1,3,9):"<<endl;
  5907. put_deque(deq1,"deq1");
  5908. //测试引用类函数
  5909. cout<<"deq1.front()="<<deq1.front()<<endl;
  5910. cout<<"deq1.back()="<<deq1.back()<<endl;
  5911. cout<<"deq1.at(4)="<<deq1.at(4)<<endl;
  5912. cout<<"deq1[4]="<<deq1[4]<<endl;
  5913. deq1.at(1)=10;
  5914. deq1[2]=12;
  5915. cout<<"deq1.at(1)=10 and deq1[2]=12 :"<<endl;
  5916. put_deque(deq1,"deq1");
  5917. //从deq1序列的前后各移去一个元素
  5918. deq1.pop_front();
  5919. deq1.pop_back();
  5920. cout<<"deq1.pop_front() and deq1.pop_back():"<<endl;
  5921. put_deque(deq1,"deq1");
  5922. //清除deq1中的第2个元素
  5923. deq1.erase(deq1.begin()+1);
  5924. cout<<"deq1.erase(deq1.begin()+1):"<<endl;
  5925. put_deque(deq1,"deq1");
  5926. //对deq2赋值并显示
  5927. deq2.assign(8,1);
  5928. cout<<"deq2.assign(8,1):"<<endl;
  5929. put_deque(deq2,"deq2");
  5930. //显示序列的状态信息
  5931. cout<<"deq1.max_size(): "<<deq1.max_size()<<endl;
  5932. cout<<"deq1.size(): "<<deq1.size()<<endl;
  5933. cout<<"deq1.empty(): "<<deq1.empty()<<endl;
  5934. //deqtor序列容器的运算
  5935. cout<<"deq1==deq3: "<<(deq1==deq3)<<endl;
  5936. cout<<"deq1<=deq3: "<<(deq1<=deq3)<<endl;
  5937. }
  5938. #include <iostream>
  5939. #include <list>
  5940. using namespace std;
  5941. typedef list<int> INTLIST;
  5942. //从前向后显示list队列的全部元素
  5943. void put_list(INTLIST list, char *name)
  5944. {
  5945. INTLIST::iterator plist;
  5946. cout << "The contents of " << name << " : ";
  5947. for(plist = list.begin(); plist != list.end(); plist++)
  5948. cout << *plist << " ";
  5949. cout<<endl;
  5950. }
  5951. //测试list容器的功能
  5952. void main(void)
  5953. {
  5954. //list1对象初始为空
  5955. INTLIST list1;
  5956. //list2对象最初有10个值为6的元素
  5957. INTLIST list2(10,6);
  5958. //list3对象最初有3个值为6的元素
  5959. INTLIST list3(list2.begin(),--list2.end());
  5960. //声明一个名为i的双向迭代器
  5961. INTLIST::iterator i;
  5962. //从前向后显示各list对象的元素
  5963. put_list(list1,"list1");
  5964. put_list(list2,"list2");
  5965. put_list(list3,"list3");
  5966. //从list1序列后面添加两个元素
  5967. list1.push_back(2);
  5968. list1.push_back(4);
  5969. cout<<"list1.push_back(2) and list1.push_back(4):"<<endl;
  5970. put_list(list1,"list1");
  5971. //从list1序列前面添加两个元素
  5972. list1.push_front(5);
  5973. list1.push_front(7);
  5974. cout<<"list1.push_front(5) and list1.push_front(7):"<<endl;
  5975. put_list(list1,"list1");
  5976. //在list1序列中间插入数据
  5977. list1.insert(++list1.begin(),3,9);
  5978. cout<<"list1.insert(list1.begin()+1,3,9):"<<endl;
  5979. put_list(list1,"list1");
  5980. //测试引用类函数
  5981. cout<<"list1.front()="<<list1.front()<<endl;
  5982. cout<<"list1.back()="<<list1.back()<<endl;
  5983. //从list1序列的前后各移去一个元素
  5984. list1.pop_front();
  5985. list1.pop_back();
  5986. cout<<"list1.pop_front() and list1.pop_back():"<<endl;
  5987. put_list(list1,"list1");
  5988. //清除list1中的第2个元素
  5989. list1.erase(++list1.begin());
  5990. cout<<"list1.erase(++list1.begin()):"<<endl;
  5991. put_list(list1,"list1");
  5992. //对list2赋值并显示
  5993. list2.assign(8,1);
  5994. cout<<"list2.assign(8,1):"<<endl;
  5995. put_list(list2,"list2");
  5996. //显示序列的状态信息
  5997. cout<<"list1.max_size(): "<<list1.max_size()<<endl;
  5998. cout<<"list1.size(): "<<list1.size()<<endl;
  5999. cout<<"list1.empty(): "<<list1.empty()<<endl;
  6000. //list序列容器的运算
  6001. put_list(list1,"list1");
  6002. put_list(list3,"list3");
  6003. cout<<"list1>list3: "<<(list1>list3)<<endl;
  6004. cout<<"list1<list3: "<<(list1<list3)<<endl;
  6005. //对list1容器排序
  6006. list1.sort();
  6007. put_list(list1,"list1");
  6008. //结合处理
  6009. list1.splice(++list1.begin(), list3);
  6010. put_list(list1,"list1");
  6011. put_list(list3,"list3");
  6012. }
  6013. #include <iostream.h>
  6014. #include <set>
  6015. using namespace std;
  6016. //创建set模板的实例
  6017. typedef set<int> SET_INT;
  6018. //put_HTset函数,从头向尾显示set容器的所有元素
  6019. void put_HTset(SET_INT set1,char *name)
  6020. {
  6021. SET_INT::iterator it;
  6022. cout<<name<<": ";
  6023. cout<<"Head to Tail=";
  6024. for (it=set1.begin();it!=set1.end();++it)
  6025. cout<<(*it)<<" ";
  6026. cout<<endl;
  6027. }
  6028. //put_THset函数,从尾向头显示set容器的所有元素
  6029. void put_THset(SET_INT s1,char *name)
  6030. {
  6031. SET_INT::reverse_iterator i;
  6032. cout<<name<<": ";
  6033. cout<<"Tail to Head=";
  6034. for (i=s1.rbegin(); i!=s1.rend();i++)
  6035. cout <<(*i) <<" ";
  6036. cout<<endl;
  6037. }
  6038. //测试set模板
  6039. void main(void)
  6040. {
  6041. int i;
  6042. //声明set的对象和迭代器
  6043. SET_INT s1; //容器初始尾空
  6044. SET_INT::iterator it;
  6045. //向s1对象中插入值
  6046. for (i=1;i<20;i=i+2) {
  6047. s1.insert(i);
  6048. }
  6049. //正向显示s1中的数据
  6050. put_HTset(s1,"s1");
  6051. //反向显示s1中的数据
  6052. put_THset(s1,"s1");
  6053. //构造含有元素的序列并显示
  6054. SET_INT s2(s1);
  6055. put_HTset(s2,"s2");
  6056. //删除s2的第2个元素并显示
  6057. s2.erase(++s2.begin());
  6058. put_HTset(s2,"s2");
  6059. //向s2插入8和9并显示
  6060. s2.insert(8);
  6061. s2.insert(9);
  6062. put_HTset(s2,"s2");
  6063. //清空s2的序列
  6064. s2.clear();
  6065. put_HTset(s2,"s2");
  6066. //按关键给定的区间显示序列中的元素
  6067. cout<<"[s1.lower_bound(5),s1.upper_bound(15)] :";
  6068. for (it=s1.lower_bound(4);it!=s1.upper_bound(16);it++)
  6069. cout<<(*it)<<" ";
  6070. cout<<endl;
  6071. //显示s1的状态信息
  6072. cout<<"s1.size():"<<s1.size()<<endl;
  6073. cout<<"s1.max_size():"<<s1.max_size()<<endl;
  6074. cout<<"s1.count(15):"<<s1.count(15)<<endl;
  6075. //交换两个set容器的元素并显示
  6076. s1.swap(s2);
  6077. put_HTset(s1,"s1");
  6078. put_HTset(s2,"s2");
  6079. //关系运算
  6080. s1.insert(5);
  6081. cout<<"s1>s2 = "<<(s1>s2)<<endl;
  6082. }
  6083. #include <iostream.h>
  6084. #include <set>
  6085. using namespace std;
  6086. //创建multiset模板的实例
  6087. typedef multiset<int> MULTISET_INT;
  6088. //put_HTset函数,从头向尾显示multiset容器的所有元素
  6089. void put_HTset(MULTISET_INT set1,char *name)
  6090. {
  6091. MULTISET_INT::iterator it;
  6092. cout<<name<<": ";
  6093. cout<<"Head to Tail=";
  6094. for (it=set1.begin();it!=set1.end();++it)
  6095. cout<<(*it)<<" ";
  6096. cout<<endl;
  6097. }
  6098. //put_THset函数,从尾向头显示multiset容器的所有元素
  6099. void put_THset(MULTISET_INT s1,char *name)
  6100. {
  6101. MULTISET_INT::reverse_iterator i;
  6102. cout<<name<<": ";
  6103. cout<<"Tail to Head=";
  6104. for (i=s1.rbegin(); i!=s1.rend();i++)
  6105. cout <<(*i) <<" ";
  6106. cout<<endl;
  6107. }
  6108. //测试multiset模板
  6109. void main(void)
  6110. {
  6111. int i;
  6112. //声明multiset的对象和迭代器
  6113. MULTISET_INT s1; //容器初始尾空
  6114. MULTISET_INT::iterator it;
  6115. //向s1对象中插入值
  6116. for (i=1;i<20;i=i+2) {
  6117. s1.insert(i);
  6118. }
  6119. //正向显示s1中的数据
  6120. put_HTset(s1,"s1");
  6121. //反向显示s1中的数据
  6122. put_THset(s1,"s1");
  6123. //构造含有元素的序列并显示
  6124. MULTISET_INT s2(s1);
  6125. put_HTset(s2,"s2");
  6126. //删除s2的第2个元素并显示
  6127. s2.erase(++s2.begin());
  6128. put_HTset(s2,"s2");
  6129. //向s2插入8和9并显示
  6130. s2.insert(8);
  6131. s2.insert(9);
  6132. put_HTset(s2,"s2");
  6133. //清空s2的序列
  6134. s2.clear();
  6135. put_HTset(s2,"s2");
  6136. //按键给定的区间显示序列中的元素
  6137. cout<<"[s1.lower_bound(5),s1.upper_bound(15)] :";
  6138. for (it=s1.lower_bound(4);it!=s1.upper_bound(16);it++)
  6139. cout<<(*it)<<" ";
  6140. cout<<endl;
  6141. //显示s1的状态信息
  6142. cout<<"s1.size():"<<s1.size()<<endl;
  6143. cout<<"s1.max_size():"<<s1.max_size()<<endl;
  6144. cout<<"s1.count(15):"<<s1.count(15)<<endl;
  6145. //交换两个multiset容器的元素并显示
  6146. s1.swap(s2);
  6147. put_HTset(s1,"s1");
  6148. put_HTset(s2,"s2");
  6149. //关系运算
  6150. s1.insert(2);
  6151. put_HTset(s1,"s1");
  6152. put_HTset(s2,"s2");
  6153. cout<<"s1>s2 = "<<(s1>s2)<<endl;
  6154. }
  6155. #include <iostream>
  6156. #include <string>
  6157. #include <map>
  6158. using namespace std;
  6159. //创建map的实例,整数(int)映射字符串(string)
  6160. typedef map<int, string> INT2STRING;
  6161. //测试map容器
  6162. void main()
  6163. {
  6164. //创建map对象theMap
  6165. INT2STRING theMap;
  6166. INT2STRING::iterator theIterator,it;
  6167. //向theMap容器中添入数据,数字和字符串配对
  6168. //每个元素是一个映射对
  6169. theMap.insert(INT2STRING::value_type(0,"Zero"));
  6170. theMap.insert(INT2STRING::value_type(2,"Two"));
  6171. theMap.insert(INT2STRING::value_type(4,"Four"));
  6172. theMap.insert(INT2STRING::value_type(6,"Six"));
  6173. theMap.insert(INT2STRING::value_type(8,"Eight"));
  6174. //显示map容器的所有对象
  6175. cout<<"theMap.begin()--theMap.end():"<<endl;
  6176. for (theIterator=theMap.begin();theIterator!=theMap.end();++theIterator){
  6177. cout<<(*theIterator).first;
  6178. cout<<","<<(*theIterator).second<<" ";
  6179. }
  6180. cout<<endl;
  6181. //测试map容器key的惟一性
  6182. theMap.insert(INT2STRING::value_type(0,"Zero"));
  6183. theMap.insert(INT2STRING::value_type(1,"One"));
  6184. theMap.insert(INT2STRING::value_type(2,"Two"));
  6185. theMap.insert(INT2STRING::value_type(3,"Three"));
  6186. theMap.insert(INT2STRING::value_type(4,"Four"));
  6187. theMap.insert(INT2STRING::value_type(5,"Five"));
  6188. theMap.insert(INT2STRING::value_type(6,"Six"));
  6189. theMap.insert(INT2STRING::value_type(7,"Seven"));
  6190. theMap.insert(INT2STRING::value_type(8,"Eight"));
  6191. theMap.insert(INT2STRING::value_type(9,"Nine"));
  6192. //下列语句将不能插入到map容器中
  6193. theMap.insert(INT2STRING::value_type(5,"AAA"));
  6194. //显示map容器的所有对象
  6195. cout<<"theMap.begin()--theMap.end():"<<endl;
  6196. for (theIterator=theMap.begin();theIterator!=theMap.end();++theIterator){
  6197. cout<<(*theIterator).first;
  6198. cout<<","<<(*theIterator).second<<" ";
  6199. }
  6200. cout<<endl;
  6201. //按键给定的区间显示序列中的元素
  6202. cout<<"[theMap.lower_bound(3),theMap.upper_bound(8)] :"<<endl;
  6203. for (it=theMap.lower_bound(3);it!=theMap.upper_bound(8);it++) {
  6204. cout<<(*it).first;
  6205. cout<<","<<(*it).second<<" ";
  6206. }
  6207. cout<<endl;
  6208. //显示theMap的状态信息
  6209. cout<<"theMap.size():"<<theMap.size()<<endl;
  6210. cout<<"theMap.max_size():"<<theMap.max_size()<<endl;
  6211. cout<<"theMap.count(15):"<<theMap.count(15)<<endl;
  6212. // 从键盘上输入数字,显示对应的字符串
  6213. string theString = "";
  6214. int index;
  6215. for( ; ; )
  6216. {
  6217. cout << "Enter \"q\" to quit, or enter a Number: ";
  6218. cin >> theString;
  6219. if(theString == "q")
  6220. break;
  6221. for(index = 0; index < theString.length(); index++){
  6222. theIterator = theMap.find(theString[index] - '0');
  6223. if(theIterator != theMap.end() )
  6224. cout << (*theIterator).second << " ";
  6225. else
  6226. cout << "[err] ";
  6227. }
  6228. cout << endl;
  6229. }
  6230. }
  6231. #include <iostream>
  6232. #include <string>
  6233. #include <map>
  6234. using namespace std;
  6235. //创建multimap的实例,整数(int)映射字符串(string)
  6236. typedef multimap<int, string> INT2STRING;
  6237. //测试multimap容器
  6238. void main()
  6239. {
  6240. //创建multimap对象theMap
  6241. INT2STRING theMap;
  6242. INT2STRING::iterator theIterator,it;
  6243. //向theMap容器中添入数据,数字和字符串配对
  6244. //每个元素是一个映射对
  6245. theMap.insert(INT2STRING::value_type(90,"张卫"));
  6246. theMap.insert(INT2STRING::value_type(85,"李华"));
  6247. theMap.insert(INT2STRING::value_type(73,"赵明"));
  6248. theMap.insert(INT2STRING::value_type(96,"郝名"));
  6249. //显示multimap容器的所有对象
  6250. cout<<"theMap.begin()--theMap.end():"<<endl;
  6251. for (theIterator=theMap.begin();theIterator!=theMap.end();++theIterator){
  6252. cout<<(*theIterator).second;
  6253. cout<<"\t"<<(*theIterator).first<<endl;
  6254. }
  6255. //测试multimap容器key的非惟一性
  6256. theMap.insert(INT2STRING::value_type(90,"李朋"));
  6257. theMap.insert(INT2STRING::value_type(85,"钱德"));
  6258. theMap.insert(INT2STRING::value_type(93,"赵刚"));
  6259. //按成绩高低输出multimap容器的所有对象
  6260. INT2STRING::reverse_iterator i;
  6261. cout<<"theMap.rbegin()--theMap.rend():"<<endl;
  6262. for (i=theMap.rbegin();i!=theMap.rend();++i){
  6263. cout<<(*i).second;
  6264. cout<<"\t"<<(*i).first<<endl;
  6265. }
  6266. //按关键给定的区间显示序列中的元素
  6267. cout<<"[theMap.lower_bound(80),theMap.upper_bound(90)] :"<<endl;
  6268. for (it=theMap.lower_bound(80);it!=theMap.upper_bound(90);it++) {
  6269. cout<<(*it).second;
  6270. cout<<"\t"<<(*it).first<<endl;
  6271. }
  6272. //显示theMap的状态信息
  6273. cout<<"theMap.size():"<<theMap.size()<<endl;
  6274. cout<<"theMap.max_size():"<<theMap.max_size()<<endl;
  6275. cout<<"theMap.count(90):"<<theMap.count(90)<<endl;
  6276. //清除90分以下的数据,并显示结果
  6277. theMap.erase(theMap.lower_bound(60),theMap.upper_bound(89));
  6278. cout<<"theMap.rbegin()--theMap.rend():"<<endl;
  6279. for (i=theMap.rbegin();i!=theMap.rend();++i){
  6280. cout<<(*i).second;
  6281. cout<<"\t"<<(*i).first<<endl;
  6282. }
  6283. }
  6284. #include <iostream>
  6285. #include <valarray>
  6286. #include <math.h>
  6287. using namespace std;
  6288. #define ARRAY_SIZE 3 //array size
  6289. //测试valarray容器
  6290. void main()
  6291. {
  6292. //创建具有3个元素的数组val_array
  6293. valarray<double> val_array(ARRAY_SIZE);
  6294. //设置数组的值为1, 4, 9
  6295. for (int i = 0; i < ARRAY_SIZE; i++)
  6296. val_array[i] = (i+1) * (i+1);
  6297. //显示val_array数组的大小
  6298. cout << "Size of val_array = " << val_array.size() << endl;
  6299. // 显示val_array数组的值
  6300. cout << "The values in val_array before calling sqrt() and pow():" << endl;
  6301. for (i = 0; i < ARRAY_SIZE; i++)
  6302. cout << val_array[i] << " ";
  6303. cout << endl;
  6304. //声明一个rev_valarray数组,其保存对数组val_array的取反
  6305. valarray<double> rev_valarray(ARRAY_SIZE);
  6306. for (i = 0; i < ARRAY_SIZE; i++)
  6307. rev_valarray[i] = val_array[ARRAY_SIZE - i - 1];
  6308. //显示rev_valarray数组的大小和元素
  6309. cout << "Size of rev_valarray = " << rev_valarray.size() << endl;
  6310. cout << "The values in rev_valarray:" << endl;
  6311. for (i = 0; i < ARRAY_SIZE; i++)
  6312. cout << rev_valarray[i] << " ";
  6313. cout <<endl;
  6314. // 声明rvalue_array数组,其存放调用sqrt()和pow()函数的返回值
  6315. valarray<double> rvalue_array;
  6316. //调用sqrt()函数并显示结果
  6317. rvalue_array = sqrt(val_array);
  6318. cout << "The result of rvalue_array after calling sqrt():" << endl;
  6319. for (i = 0; i < ARRAY_SIZE; i++)
  6320. cout << rvalue_array[i] << " ";
  6321. cout <<endl;
  6322. //对val_array数组元素计算幂函数并显示
  6323. rvalue_array = pow(val_array, rev_valarray);
  6324. cout << "The result after calling pow(val_array, rev_valarray):"
  6325. << endl;
  6326. for (i = 0; i < ARRAY_SIZE; i++)
  6327. cout << rvalue_array[i] << " ";
  6328. cout <<endl;
  6329. //对val_array数组元素计算幂函数,指数均为2.0,并显示
  6330. rvalue_array = pow(val_array, 2.0);
  6331. cout << "The result after calling pow(val_array, 2.0):" << endl;
  6332. for (i = 0; i < ARRAY_SIZE; i++)
  6333. cout << rvalue_array[i] << " ";
  6334. cout <<endl;
  6335. //对2.0进行幂函数运算,指数均为数组val_array的各元素值
  6336. rvalue_array = pow(2.0, val_array);
  6337. cout << "The result after calling pow(2.0, val_array):" << endl;
  6338. for (i = 0; i < ARRAY_SIZE; i++)
  6339. cout << rvalue_array[i] << " ";
  6340. cout <<endl;
  6341. //对val_array和rvalue_array求和
  6342. cout<<"val_array.sum()="<<val_array.sum()<<endl;
  6343. cout<<"rvalue_array.sum()="<<rvalue_array.sum()<<endl;
  6344. //求最大值并显示
  6345. cout<<"val_array.max()="<<val_array.max()<<endl;
  6346. cout<<"rvalue_array.max()="<<rvalue_array.max()<<endl;
  6347. }
  6348. #include <stack>
  6349. #include <iostream>
  6350. using namespace std ;
  6351. typedef stack<int> STACK_INT;
  6352. void main()
  6353. {
  6354. STACK_INT stack1;
  6355. int i;
  6356. //判断栈是否空
  6357. cout << "stack1.empty() returned " <<
  6358. (stack1.empty()? "true": "false") << endl;
  6359. //0,2,4,6...入栈
  6360. for (i=0;i<10;i=i+2)
  6361. stack1.push(i);
  6362. //top()函数
  6363. if (!stack1.empty())
  6364. cout << "stack1.top() returned " <<stack1.top() << endl;
  6365. //计算栈的长度
  6366. cout<<"stack1.size(): "<<stack1.size()<<endl;
  6367. //改变栈顶的值 20.
  6368. if (!stack1.empty()) {
  6369. cout << "stack1.top()=20;" << endl;
  6370. stack1.top()=20;
  6371. }
  6372. //弹出栈中所有的数据并显示
  6373. cout<<"stack1: ";
  6374. while (!stack1.empty()) {
  6375. cout<<stack1.top()<<" ";
  6376. stack1.pop();
  6377. }
  6378. cout<<endl;
  6379. }
  6380. #include <iostream>
  6381. #include <list>
  6382. #include <numeric>
  6383. using namespace std;
  6384. //创建一个list容器的实例LISTINT,其存放int型数据
  6385. typedef list<int> LISTINT;
  6386. void main(void)
  6387. {
  6388. //用LISTINT创建一个名为listOne的list对象
  6389. LISTINT listOne;
  6390. //指定i为迭代器变量
  6391. LISTINT::iterator i;
  6392. LISTINT::reverse_iterator ir;
  6393. //从前面向listOne容器中添加数据
  6394. listOne.push_front (2);
  6395. listOne.push_front (1);
  6396. //从后面向listOne容器中添加数据
  6397. listOne.push_back (3);
  6398. listOne.push_back (4);
  6399. //从前向后显示listOne中的数据
  6400. for (i = listOne.begin(); i != listOne.end(); ++i)
  6401. cout << *i << " ";
  6402. cout << endl;
  6403. //从后向后显示listOne中的数据
  6404. for (ir =listOne.rbegin();ir!=listOne.rend(); ++ir)
  6405. cout << *ir << " ";
  6406. cout << endl;
  6407. //从键盘上输入数据
  6408. for (i = listOne.begin(); i != listOne.end(); ++i) {
  6409. cout<<"listOne :";
  6410. cin>>(*i);
  6411. }
  6412. //从前向后显示listOne中的数据
  6413. for (i = listOne.begin(); i != listOne.end(); ++i)
  6414. cout << *i << " ";
  6415. cout << endl;
  6416. //bidirectional迭代器不允许加减运算
  6417. // i=listOne.begin()+1;
  6418. }
  6419. #include <iostream>
  6420. #include <iostream>
  6421. #include <numeric>
  6422. #include <vector>
  6423. #include <list>
  6424. #include <set>
  6425. using namespace std;
  6426. //利用类模板生成类实例
  6427. typedef vector < int > IntArray;
  6428. typedef list <int> LISTINT;
  6429. typedef set<int> SET_INT;
  6430. int add(int a, int b) {
  6431. return a+b;
  6432. }
  6433. //在main()函数中测试accumulate算法
  6434. void main ()
  6435. {
  6436. //--------------------------------------------
  6437. // accumulate算法对于普通数组的计算
  6438. //---------------------------------------------
  6439. int x[]={1,3,5,7,9};
  6440. cout<<"x[]:";
  6441. for (int i=0;i<5;i++)
  6442. cout<<x[i]<<" ";
  6443. cout<<endl;
  6444. cout<<"accumulate(x,x+5,0)=";
  6445. cout<<accumulate(x,x+5,0)<<endl;
  6446. int val=100;
  6447. cout<<"val="<<val<<endl;
  6448. cout<<"accumulate(x,x+5,val)=";
  6449. cout<<accumulate(x,x+5,val)<<endl;
  6450. //--------------------------------------------
  6451. // accumulate算法对于vector容器的计算
  6452. //---------------------------------------------
  6453. //声明intvector容器和迭代器ii
  6454. IntArray intvector;
  6455. IntArray::iterator ii;
  6456. //向intvector容器中插入元素
  6457. for (i=1; i<=5; i++) {
  6458. intvector.push_back(i);
  6459. };
  6460. //显示intvector容器中的元素值和累加结果
  6461. cout << "intvector: "<<endl;
  6462. for (ii=intvector.begin();ii !=intvector.end();++ii)
  6463. cout<<(*ii)<<" ";
  6464. cout<<endl;
  6465. cout<<"accumulate(intvector.begin(),intvector.end(),0)=";
  6466. cout<<accumulate(intvector.begin(),intvector.end(),0)<<endl;
  6467. //--------------------------------------------
  6468. // accumulate算法对于list容器的计算
  6469. //---------------------------------------------
  6470. //声明list容器对象和迭代器
  6471. LISTINT::iterator iL;
  6472. LISTINT list1;
  6473. //向list1容器对象中插入元素并显示
  6474. list1.push_front(1);
  6475. list1.push_front(3);
  6476. list1.push_front(5);
  6477. list1.push_back(2);
  6478. list1.push_back(6);
  6479. //显示list1容器的元素值和累加结果
  6480. cout << "list1: "<<endl;
  6481. for (iL=list1.begin();iL !=list1.end();++iL)
  6482. cout<<(*iL)<<" ";
  6483. cout<<endl;
  6484. cout<<"accumulate(list1.begin(),list1.end(),0)=";
  6485. cout<<accumulate(list1.begin(),list1.end(),0)<<endl;
  6486. //--------------------------------------------
  6487. // accumulate算法对于set容器的计算
  6488. //---------------------------------------------
  6489. //声明set容器对象和迭代器
  6490. SET_INT set1;
  6491. SET_INT::iterator si;
  6492. //向set1容器中插入元素
  6493. set1.insert(5);
  6494. set1.insert(20);
  6495. set1.insert(10);
  6496. set1.insert(15);
  6497. set1.insert(25);
  6498. //显示set1容器的元素值和累加结果
  6499. cout <<"set1: "<<endl;
  6500. for (si=set1.begin();si !=set1.end();++si)
  6501. cout<<(*si)<<" ";
  6502. cout<<endl;
  6503. cout<<"accumulate(set1.begin(),set1.end(),0)=";
  6504. cout<<accumulate(set1.begin(),set1.end(),0)<<endl;
  6505. cout<<"accumulate(set1.begin(),set1.end(),100)=";
  6506. cout<<accumulate(set1.begin(),set1.end(),100)<<endl;
  6507. }
  6508. #include <iostream>
  6509. #include <algorithm>
  6510. #include <vector>
  6511. #include <list>
  6512. #include <set>
  6513. #define size 10
  6514. using namespace std;
  6515. //产生指定范围的整数随机数
  6516. int getrand(int min,int max) {
  6517. int m;
  6518. m=(max-min);
  6519. m=min+double(rand())/RAND_MAX*m ;
  6520. return m;
  6521. }
  6522. //利用类模板生成实例
  6523. typedef vector < int > IntArray;
  6524. typedef list <int> LISTINT;
  6525. typedef set<int> SET_INT;
  6526. //在main()函数中测试accumulate算法
  6527. void main ()
  6528. {
  6529. //--------------------------------------------
  6530. // count算法对于普通数组的计算
  6531. //---------------------------------------------
  6532. int x[size];
  6533. cout<<"x[]:";
  6534. for (int i=0;i<size;i++) {
  6535. x[i]=getrand(1,3);
  6536. cout<<x[i]<<" ";
  6537. }
  6538. cout<<endl;
  6539. cout<<"count(x,x+size,2)=";
  6540. cout<<count(x,x+size,2)<<endl;
  6541. cout<<"count(x+2,x+8,2)=";
  6542. cout<<count(x+2,x+8,2)<<endl;
  6543. //--------------------------------------------
  6544. // count算法对于vector容器的计算
  6545. //---------------------------------------------
  6546. //声明intvector容器和迭代器ii
  6547. IntArray intvector;
  6548. IntArray::iterator ii;
  6549. //向intvector容器中插入元素
  6550. for (i=1; i<size; i++) {
  6551. intvector.push_back(getrand(2,6));
  6552. };
  6553. //显示intvector容器中的元素值和统计结果
  6554. cout << "intvector: ";
  6555. for (ii=intvector.begin();ii !=intvector.end();++ii)
  6556. cout<<(*ii)<<" ";
  6557. cout<<endl;
  6558. cout<<"count(intvector.begin(),intvector.end(),4)=";
  6559. cout<<count(intvector.begin(),intvector.end(),4)<<endl;
  6560. //--------------------------------------------
  6561. // count算法对于list容器的计算
  6562. //---------------------------------------------
  6563. //声明list容器对象和迭代器
  6564. LISTINT::iterator iL;
  6565. LISTINT list1;
  6566. //向list1容器对象中插入元素并显示
  6567. for (i=1; i<size; i++) {
  6568. list1.push_front(getrand(3,5));
  6569. };
  6570. //显示list1容器的元素值和统计结果
  6571. cout << "list1: ";
  6572. for (iL=list1.begin();iL !=list1.end();++iL)
  6573. cout<<(*iL)<<" ";
  6574. cout<<endl;
  6575. cout<<"count(list1.begin(),list1.end(),3)=";
  6576. cout<<count(list1.begin(),list1.end(),3)<<endl;
  6577. //--------------------------------------------
  6578. // count算法对于set容器的计算
  6579. //---------------------------------------------
  6580. //声明set容器对象和迭代器
  6581. SET_INT set1;
  6582. SET_INT::iterator si;
  6583. //向set1容器中插入元素
  6584. for (i=1; i<size; i++) {
  6585. set1.insert(getrand(1,10));
  6586. };
  6587. //显示set1容器的元素值和统计结果
  6588. cout <<"set1: ";
  6589. for (si=set1.begin();si !=set1.end();++si)
  6590. cout<<(*si)<<" ";
  6591. cout<<endl;
  6592. cout<<"count(set1.begin(),set1.end(),5)=";
  6593. cout<<count(set1.begin(),set1.end(),5)<<endl;
  6594. }
  6595. #include <iostream>
  6596. #include <algorithm>
  6597. #include <string>
  6598. #include <vector>
  6599. using namespace std;
  6600. //如果字符串以'S'开头,则返回true
  6601. int MatchFirstChar( const string& str)
  6602. {
  6603. string s("S") ;
  6604. return s == str.substr(0,1) ;
  6605. }
  6606. //测试count_if算法
  6607. void main()
  6608. {
  6609. const int VECTOR_SIZE = 8 ;
  6610. //生成成员类型为strings的vector容器类
  6611. typedef vector<string > StringVector ;
  6612. //定义迭代器类型
  6613. typedef StringVector::iterator StringVectorIt ;
  6614. //声明vector容器的对象
  6615. StringVector NamesVect(VECTOR_SIZE) ;
  6616. //声明迭代器
  6617. StringVectorIt start, end, it ;
  6618. int result = 0 ; // 存放统计数据
  6619. //初始化vector容器NamesVect
  6620. NamesVect[0] = "She" ;
  6621. NamesVect[1] = "Sells" ;
  6622. NamesVect[2] = "Sea" ;
  6623. NamesVect[3] = "Shells" ;
  6624. NamesVect[4] = "by" ;
  6625. NamesVect[5] = "the" ;
  6626. NamesVect[6] = "Sea" ;
  6627. NamesVect[7] = "Shore" ;
  6628. //设置容器的起始位置和终止位置
  6629. start = NamesVect.begin() ;
  6630. end = NamesVect.end() ;
  6631. //显示NamesVect容器的元素
  6632. cout << "NamesVect: " ;
  6633. for(it = start; it != end; it++)
  6634. cout << *it << " " ;
  6635. cout <<endl ;
  6636. //统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串
  6637. result = count_if(start, end, MatchFirstChar) ;
  6638. cout << "Number of elements that start with letter \"S\" = "
  6639. << result << endl ;
  6640. //显示NamesVect容器[1,6]之间的元素
  6641. cout <<"NamesVect[1]--NamesVect[6]: " ;
  6642. for(it =&NamesVect[1]; it != &NamesVect[7]; it++)
  6643. cout << *it << " " ;
  6644. cout <<endl ;
  6645. //统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串
  6646. result = count_if(&NamesVect[1], &NamesVect[7], MatchFirstChar) ;
  6647. cout << "Number of elements that start with letter \"S\" = "
  6648. << result << endl ;
  6649. }
  6650. #include <iostream>
  6651. #include <algorithm>
  6652. #include <vector>
  6653. using namespace std;
  6654. //利用类模板生成实例
  6655. typedef vector < int > IntArray;
  6656. //显示数组
  6657. void put_array(int x[],int size) {
  6658. for(int i=0;i<size;i++)
  6659. cout<<x[i]<<" ";
  6660. cout<<endl;
  6661. }
  6662. //显示vector容器中的元素
  6663. void put_vector(IntArray v)
  6664. {
  6665. IntArray::iterator theIterator;
  6666. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  6667. cout<<(*theIterator)<<" ";
  6668. }
  6669. cout<<endl;
  6670. }
  6671. //在main()函数中测试fill和fill_n算法
  6672. void main ()
  6673. {
  6674. //--------------------------------------------
  6675. // fill和fill_n算法对普通数组的计算
  6676. //---------------------------------------------
  6677. int x[]={1,3,5,7,9};
  6678. cout << "x[]: ";
  6679. put_array(x,5);
  6680. //填数处理
  6681. fill(x+1,x+3,2);
  6682. cout << "fill(x+1,x+3,2): "<<endl;
  6683. put_array(x,5);
  6684. fill_n(x,3,8);
  6685. cout << "fill_n(x,3,8): "<<endl;
  6686. put_array(x,5);
  6687. //--------------------------------------------
  6688. // fill和fill_n算法对于vector容器的计算
  6689. //---------------------------------------------
  6690. //声明intvector容器和迭代器ii
  6691. IntArray intvector;
  6692. //向intvector容器中插入元素
  6693. for (int i=1; i<=10; i++) {
  6694. intvector.push_back(i);
  6695. };
  6696. //显示intvector容器中的元素值和统计结果
  6697. cout << "intvector: "<<endl;
  6698. put_vector(intvector);
  6699. //填数处理
  6700. fill(intvector.begin(),intvector.begin()+3,2);
  6701. cout << "fill(intvector.begin(),intvector.begin()+3,2): "<<endl;
  6702. put_vector(intvector);
  6703. fill_n(&intvector[5],3,8);
  6704. cout << "fill_n(&intvector[5],3,8): "<<endl;
  6705. put_vector(intvector);
  6706. }
  6707. #include <iostream>
  6708. #include <algorithm>
  6709. #include <vector>
  6710. #define ARRAY_SIZE 10
  6711. using namespace std;
  6712. //利用类模板生成实例
  6713. typedef vector < int > IntArray;
  6714. //显示数组
  6715. void put_array(int x[],int size) {
  6716. for(int i=0;i<size;i++)
  6717. cout<<x[i]<<" ";
  6718. cout<<endl;
  6719. }
  6720. //显示vector容器中的元素
  6721. void put_vector(IntArray v)
  6722. {
  6723. IntArray::iterator theIterator;
  6724. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  6725. cout<<(*theIterator)<<" ";
  6726. }
  6727. cout<<endl;
  6728. }
  6729. //在main()函数中测试find()算法
  6730. void main ()
  6731. {
  6732. int i,value,*p;
  6733. //--------------------------------------------
  6734. // find()算法对于普通数组的处理
  6735. //---------------------------------------------
  6736. int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10};
  6737. cout << "x[]: ";
  6738. put_array(x,ARRAY_SIZE);
  6739. //find()算法查找,并显示查找结果
  6740. for(i=0;i<=2;i++) {
  6741. cout<<"value=";
  6742. cin>>value;
  6743. p=find(x,x+ARRAY_SIZE,value);
  6744. if (p != x + ARRAY_SIZE) { //查到
  6745. cout << "First element that matches " << value;
  6746. cout<< " is at location " << p - x<< endl;
  6747. }
  6748. else { //未查到
  6749. cout << "The sequence does not contain any elements";
  6750. cout<< " with value " << value << endl ;
  6751. }
  6752. }
  6753. //--------------------------------------------
  6754. // find()算法对于vector容器的处理
  6755. //---------------------------------------------
  6756. //声明intvector容器对象
  6757. IntArray intvector;
  6758. //向intvector容器中插入元素
  6759. for (i=1; i<=10; i++) {
  6760. intvector.push_back(i);
  6761. };
  6762. //显示intvector容器中的元素值
  6763. cout << "intvector: ";
  6764. put_vector(intvector);
  6765. //find()算法查找,并显示查找结果
  6766. IntArray::iterator pos;
  6767. for (i=0;i<=2;i++) {
  6768. cout<<"value=";
  6769. cin>>value;
  6770. pos=find(intvector.begin(),intvector.end(),value);
  6771. if (pos != intvector.end()) { //查到
  6772. cout << "First element that matches " << value;
  6773. cout<< " is at location " <<pos - intvector.begin()<< endl;
  6774. }
  6775. else { //未查到
  6776. cout << "The sequence does not contain any elements";
  6777. cout<< " with value " << value << endl ;
  6778. }
  6779. }
  6780. }
  6781. #include <iostream>
  6782. #include <algorithm>
  6783. #include <vector>
  6784. #define ARRAY_SIZE 10
  6785. using namespace std;
  6786. //利用类模板生成实例
  6787. typedef vector < int > IntArray;
  6788. //显示数组
  6789. void put_array(int x[],int size) {
  6790. for(int i=0;i<size;i++)
  6791. cout<<x[i]<<" ";
  6792. }
  6793. //显示vector容器中的元素
  6794. void put_vector(IntArray v)
  6795. {
  6796. IntArray::iterator theIterator;
  6797. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  6798. cout<<(*theIterator)<<" ";
  6799. }
  6800. }
  6801. //在main()函数中测试find()_end()算法
  6802. void main ()
  6803. {
  6804. //--------------------------------------------
  6805. // find_end()算法对普通数组的处理
  6806. //---------------------------------------------
  6807. int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10};
  6808. cout << "x[]: ";
  6809. put_array(x,ARRAY_SIZE);
  6810. cout<<endl;
  6811. int y[]={5,7,9};
  6812. cout << "y[]: ";
  6813. put_array(y,3);
  6814. cout<<endl;
  6815. // find_end()算法查找,并显示查找结果
  6816. int *p=find_end(x,x+ARRAY_SIZE,&y[0],&y[2]);
  6817. if (p != x + ARRAY_SIZE) { //查到
  6818. cout << "The first element that matches :" ;
  6819. put_array(y,3);
  6820. cout<< " is at location in x" << p - x<< endl;
  6821. }
  6822. else { //未查到
  6823. cout << "The sequence does not contain any elements";
  6824. cout<< " with value " ;
  6825. put_array(&x[3],3);
  6826. }
  6827. //--------------------------------------------
  6828. // find_end()算法对vector容器的处理
  6829. //---------------------------------------------
  6830. //声明intvector容器对象
  6831. IntArray intvector;
  6832. //向intvector容器中插入元素
  6833. for (int i=1; i<=10; i++) {
  6834. intvector.push_back(i);
  6835. };
  6836. //显示intvector容器中的元素值
  6837. cout << "intvector: ";
  6838. put_vector(intvector);
  6839. cout<<endl;
  6840. IntArray temp;
  6841. temp.push_back(5);
  6842. temp.push_back(6);
  6843. temp.push_back(7);
  6844. cout << "temp: ";
  6845. put_vector(temp);
  6846. cout<<endl;
  6847. // find_end()算法查找,并显示查找结果
  6848. IntArray::iterator pos;
  6849. pos=find_end(intvector.begin(),intvector.end(),temp.begin(),temp.end());
  6850. if (pos != intvector.end()) { //查到
  6851. cout << "The first element that matches ";
  6852. put_vector(temp);
  6853. cout<< " is at location in intvector " <<pos - intvector.begin()<< endl;
  6854. }
  6855. else { //未查到
  6856. cout << "The sequence does not contain any elements";
  6857. cout<< " with value ";
  6858. put_vector(temp);
  6859. cout<< endl ;
  6860. }
  6861. }
  6862. #include <iostream>
  6863. #include <vector>
  6864. #include <algorithm>
  6865. using namespace std;
  6866. //返回一个Fibonacci数,其由generate_n()算法调用
  6867. int Fibonacci1(void)
  6868. {
  6869. static int r;
  6870. static int f1 = 0;
  6871. static int f2 = 1;
  6872. r = f1 + f2 ;
  6873. f1 = f2 ;
  6874. f2 = r ;
  6875. return f1 ;
  6876. }
  6877. //返回一个Fibonacci数,其由generate()算法调用
  6878. int Fibonacci2(void)
  6879. {
  6880. static int r;
  6881. static int f1 = 0;
  6882. static int f2 = 1;
  6883. r = f1 + f2 ;
  6884. f1 = f2 ;
  6885. f2 = r ;
  6886. return f1 ;
  6887. }
  6888. //定义整型数的vector容器类
  6889. typedef vector<int > IntVector ;
  6890. //显示vector容器中的元素
  6891. void put_vector(IntVector v,char *name)
  6892. {
  6893. IntVector::iterator theIterator;
  6894. cout<<name<<":"<<endl;
  6895. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  6896. cout<<(*theIterator)<<" ";
  6897. }
  6898. cout<<endl;
  6899. }
  6900. //测试generate()和generate_n()算法
  6901. void main()
  6902. {
  6903. const int VECTOR_SIZE = 15 ;
  6904. //定义迭代器类
  6905. typedef IntVector::iterator IntVectorIt ;
  6906. //声明vector容器对象
  6907. IntVector Numbers1(VECTOR_SIZE),Numbers2(VECTOR_SIZE);
  6908. int i ;
  6909. //初始化vector容器对象
  6910. for(i = 0; i < VECTOR_SIZE; i++)
  6911. Numbers1[i] = i ;
  6912. //显示vector容器对象的元素
  6913. cout << "Before calling generate_n:" << endl ;
  6914. put_vector(Numbers1,"Numbers1");
  6915. //利用generate_n算法用Fibonacci 数填充vector容器
  6916. generate_n(Numbers1.begin(), VECTOR_SIZE, Fibonacci1) ;
  6917. //显示vector容器对象的元素
  6918. cout << "After calling generate_n:" << endl ;
  6919. put_vector(Numbers1,"Numbers1");
  6920. //利用generate算法用Fibonacci 数填充vector容器
  6921. generate(Numbers2.begin(),Numbers2.end(), Fibonacci2) ;
  6922. //显示vector容器对象的元素
  6923. cout << "After calling generate:" << endl ;
  6924. put_vector(Numbers2,"Numbers2");
  6925. }
  6926. #include <iostream>
  6927. #include <algorithm>
  6928. #include <vector>
  6929. using namespace std;
  6930. //利用类模板生成实例
  6931. typedef vector < int > IntArray;
  6932. //显示数组
  6933. void put_array(int x[],int size) {
  6934. for(int i=0;i<size;i++)
  6935. cout<<x[i]<<" ";
  6936. cout<<endl;
  6937. }
  6938. //显示vector容器中的元素
  6939. void put_vector(IntArray v)
  6940. {
  6941. IntArray::iterator theIterator;
  6942. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  6943. cout<<(*theIterator)<<" ";
  6944. }
  6945. cout<<endl;
  6946. }
  6947. //在main()函数中测试reverse()和reverse_copy()算法
  6948. void main ()
  6949. {
  6950. //--------------------------------------------
  6951. // reverse()和reverse_copy()算法对普通数组处理
  6952. //---------------------------------------------
  6953. int x[]={1,3,5,7,9};
  6954. cout<<"x[]:";
  6955. put_array(x,5);
  6956. //reverse()反转x数组并显示
  6957. reverse(x,x+5);
  6958. cout<<"x[]:";
  6959. put_array(x,5);
  6960. int y[]={2,4,6,8,10};
  6961. cout<<"y[]:";
  6962. put_array(y,5);
  6963. //reverse_copy()反转y数组的部分元素并拷贝到x数组第2个元素位置
  6964. reverse_copy(y+1,y+3,x+1);
  6965. cout<<"x[]:";
  6966. put_array(x,5);
  6967. cout<<"y[]:";
  6968. put_array(y,5);
  6969. //--------------------------------------------
  6970. // reverse()和reverse_copy()算法对vector容器的处理
  6971. //---------------------------------------------
  6972. //声明intvector容器和迭代器ii
  6973. IntArray intvector;
  6974. //向intvector容器中插入元素
  6975. for (int i=1; i<=10; i++) {
  6976. intvector.push_back(i);
  6977. };
  6978. //显示intvector容器中的元素值
  6979. cout << "intvector: "<<endl;
  6980. put_vector(intvector);
  6981. //reverse()对于vector容器的处理
  6982. reverse(intvector.begin(),intvector.end());
  6983. cout << "intvector: "<<endl;
  6984. put_vector(intvector);
  6985. // reverse_copy对于vector容器的处理
  6986. IntArray temp(5);
  6987. reverse_copy(intvector.begin()+2,intvector.begin()+7,temp.begin());
  6988. cout << "temp: "<<endl;
  6989. put_vector(temp);
  6990. }
  6991. #include <iostream>
  6992. #include <algorithm>
  6993. #include <vector>
  6994. #include <stdlib.h>
  6995. #define ARRAY_SIZE 15
  6996. using namespace std;
  6997. //定义整型数的vector容器类
  6998. typedef vector<int > IntVector ;
  6999. //显示数组
  7000. void put_array(int x[],int size) {
  7001. for(int i=0;i<size;i++)
  7002. cout<<x[i]<<" ";
  7003. cout<<endl;
  7004. }
  7005. //显示vector容器中的元素
  7006. void put_vector(IntVector v,char *name)
  7007. {
  7008. IntVector::iterator theIterator;
  7009. cout<<name<<": ";
  7010. for (theIterator=v.begin();theIterator!=v.end();++theIterator){
  7011. cout<<(*theIterator)<<" ";
  7012. }
  7013. cout<<endl;
  7014. }
  7015. //产生指定范围的整数随机数
  7016. int getrand(int min,int max) {
  7017. int m;
  7018. m=(max-min);
  7019. m=min+double(rand())/RAND_MAX*m ;
  7020. return m;
  7021. }
  7022. //在main()函数中测试sort()和partial_sort()算法
  7023. void main ()
  7024. {
  7025. int i;
  7026. //--------------------------------------------
  7027. // sort()和partial_sort()算法对普通数组处理
  7028. //---------------------------------------------
  7029. //sort()算法处理数组,并显示
  7030. int x[ARRAY_SIZE];
  7031. for (i=0;i<ARRAY_SIZE;i++) {
  7032. x[i]=getrand(1,20);
  7033. }
  7034. cout<<"x[]:";
  7035. put_array(x,ARRAY_SIZE);
  7036. sort(x,x+ARRAY_SIZE);
  7037. cout<<"sort(x,x+ARRAY_SIZE):"<<endl;
  7038. put_array(x,ARRAY_SIZE);
  7039. //partial_sort()算法对于数组进行处理
  7040. int y[ARRAY_SIZE];
  7041. for (i=0;i<ARRAY_SIZE;i++) {
  7042. y[i]=getrand(1,30) ;
  7043. }
  7044. cout<<"y[]:";
  7045. put_array(y,ARRAY_SIZE);
  7046. partial_sort(y+2,y+7,y+ARRAY_SIZE);
  7047. cout<<"partial_sort(y+2,y+7,y+ARRAY_SIZE):"<<endl;
  7048. put_array(y,ARRAY_SIZE);
  7049. //--------------------------------------------
  7050. // sort()和partial_sort()算法对vector容器的处理
  7051. //---------------------------------------------
  7052. IntVector Numbers1,Numbers2;
  7053. for(i=0;i<15;i++) {
  7054. Numbers1.push_back(getrand(1,30));
  7055. Numbers2.push_back(getrand(1,30));
  7056. }
  7057. put_vector(Numbers1,"Numbers1");
  7058. put_vector(Numbers2,"Numbers2");
  7059. //sort()算法处理并显示
  7060. sort(Numbers1.begin(),Numbers1.end());
  7061. cout<<"After call sort():"<<endl;
  7062. put_vector(Numbers1,"Numbers1");
  7063. //partial_sort()算法处理并显示
  7064. partial_sort(Numbers2.begin()+2,Numbers2.begin()+7,Numbers2.end());
  7065. cout<<"After call partial_sort():"<<endl;
  7066. put_vector(Numbers2,"Numbers2");
  7067. }
  7068. #include <iostream>
  7069. #include <algorithm>
  7070. #include <stdlib.h>
  7071. #include <time.h>
  7072. #define ARRAY_SIZE 15
  7073. using namespace std;
  7074. //显示数组
  7075. void put_array(int x[],int size) {
  7076. for(int i=0;i<size;i++)
  7077. cout<<x[i]<<" ";
  7078. cout<<endl;
  7079. }
  7080. //产生指定范围的整数随机数
  7081. int getrand(int min,int max) {
  7082. int m;
  7083. m=(max-min);
  7084. m=min+double(rand())/RAND_MAX*m ;
  7085. return m;
  7086. }
  7087. //在main()函数中测试max_element()和 min_element()算法
  7088. void main ()
  7089. {
  7090. //声明变量和数组
  7091. int i;
  7092. int x[ARRAY_SIZE];
  7093. //用1到100的随机数初始化数组,并显示
  7094. srand( (unsigned)time( NULL ) );
  7095. for (i=0;i<ARRAY_SIZE;i++) {
  7096. x[i]=getrand(1,100);
  7097. }
  7098. cout<<"x[]:";
  7099. put_array(x,ARRAY_SIZE);
  7100. //对数组x使用max_element()算法,并显示
  7101. int *pMax=max_element(x,x+ARRAY_SIZE);
  7102. cout<<"pMax ="<<pMax<<endl;
  7103. cout<<"Location="<<(pMax-x)<<endl;
  7104. cout<<"*pMax ="<<(*pMax)<<endl;
  7105. //对数组x使用min_element()算法,并显示
  7106. int *pMin=min_element(x,x+ARRAY_SIZE);
  7107. cout<<"pMin ="<<pMin<<endl;
  7108. cout<<"Location="<<(pMin-x)<<endl;
  7109. cout<<"*pMin ="<<(*pMin)<<endl;
  7110. }


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/604528
推荐阅读
相关标签
  

闽ICP备14008679号