我们在可以将程序运行时的信息输出到用户控制台或者文件,以便调试。为函数提供默认参数可以来控制是否输出程序运行时的日志信息。以下以冒泡排序为例,以Essential C++中的源码为基础。
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
inline void swap(int& i, int& j){
auto temp = i;
i = j;
j = temp;
}
void bubble_sort(vector<int> & ivc, ofstream *ofil = 0){
for (int ix = 0; ix != ivc.size(); ++ix)
for (int jx = ix+1; jx != ivc.size(); ++jx)
if (ivc[ix] > ivc[jx]){
if (ofil != 0)
*ofil << "swap " << ivc[ix] << " and " << ivc[jx] << endl;
swap(ivc[ix], ivc[jx]);
}
}
//test
int main(){
vector<int> ivc1{1,5,3,6,2,9,7,8}, ivc2(ivc1);
//close log
bubble_sort(ivc1);
for (auto i : ivc1)
cout << i << ' ';
cout << endl;
//open log
ofstream log("log.txt");
ofstream* ofil = &log;
bubble_sort(ivc2, ofil);
for (auto j : ivc2)
cout << j << ' ';
cout << endl;
return 0;
}