C++ Primer 6.5.3节练习

练习 6.47: 改写6.3.2节(第205页)练习中使用递归输出vector内容的程序,使其有条件地输出与执行过程有关的信息。例如,每次调用时输出vector对象的大小。分别在打开和关闭调试器的情况下编译并执行这个程序。

///这一题需要在前面输出vector内容的程序中,添加新的功能————>有条件地输出与执行过程有关的信息

    为了简便解答该题,我们采用vector引用,vector的类型是string型,在过程中不改变容器大小。

 经过测试得到一个现象,编译器将会按照 #define DEBUG  #ifndef DEBUG  .......中两者的先后顺序而进行读取,即谁的位置在前,读谁。为了正常运行指令,我们需要将main()主函数放到调用函数前面的位置。

代码如下:

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <string>
 4 #include <cctype>
 5 #include <cstring>
 6 #include <vector> 7 
 8 
 9 using namespace std;              ////声明命名空间
10 void printvec(vector<string>&, int);  ///声明该函数
11 
12 int main()
13 {
14     #define DEBUG                   ////在主函数的开头添加预处理变量
15     vector<string> sub = { "兄弟","你好","我可以给你来两下?" };
16     printvec(sub, 0);                                     
17     return 0;
18  }
19 void printvec(vector<string>& vec, int cnt)///形参:(容器,计算器)
20 {
21 
22 #ifndef DEBUG
23     cout << vec.size() << endl;            ///输出vector对象大小
24 #endif // !DEBUG
25 
26 
27 
28     if (cnt != vec.size())
29     {
30         cout << vec[cnt] << endl;
31         printvec(vec, ++cnt);
32     }
33 
34 }

猜你喜欢

转载自www.cnblogs.com/Fengyuyang/p/9085807.html