调试--默认参数控制调试信息的输出与否

我们在可以将程序运行时的信息输出到用户控制台或者文件,以便调试。为函数提供默认参数可以来控制是否输出程序运行时的日志信息。以下以冒泡排序为例,以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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值