1. 程式人生 > >C++ Primer 6.5.3節練習

C++ Primer 6.5.3節練習

pri clu 位置 std color class 簡便 sof end

練習 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 }

C++ Primer 6.5.3節練習