练习6.47:改写6.3.2节(第205页)练习中使用递归输出vector内容的程序,使其有条件地输出与执行过程有关的信息。例如,每次调用时输出vector对象的大小。分别在打开和关闭调试器的情况下编译并执行这个程序。
练习6.48:说明下面这个循环的含义,它对assert的使用合理吗?
string s;
while (cin >> s && s != sought) {} //空函数体
assert(cin);
答:不合理,当不再输入,或者s = sought时,此时cin为空,表达式求值为假,断言实现,输出错误信息,并退出程序。
练习6.47
/*
*练习6.47
*2015/6/25
*问题描述:练习6.47:改写6.3.2节(第205页)练习中使用递归输出vector内容的程序,使其有条件地输出与执行过程有关的信息。例如,每次调用时输出vector对象的大小。分别在打开和关闭调试器的情况下编译并执行这个程序。
*功能:递归改写
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*
*/
#include <iostream>
#include <vector>
using namespace std;
void print(vector<string> vec, vector<string>::size_type n) //
{
if (n != vec.size()-1)
print(vec,n+1);
cout << vec[n] <<" ";
}
void print_debug(vector<string> vec, vector<string>::size_type n) //关闭调试状态
{
#ifndef NDEBUG
cerr << __func__ << ": size is " << vec.size() << endl;
#endif
if (n != vec.size()-1)
cout << vec[n] <<" ";
print(vec,n+1);
}
void print_debug_2(vector<string> vec, vector<string>::size_type n)//打开调试状态
{
cerr << __func__ << ": size is " << vec.size() << endl;
if (n != vec.size()-1)
cout << vec[n] <<" ";
print(vec,n+1);
}
int main()
{
vector<string> vec;
string s;
while (cin >> s)
vec.push_back(s);
vector<string>::size_type n = 0;
print(vec,n);
cout << endl;
print_debug(vec,n);
cout << endl;
print_debug_2(vec,n);
return 0;
}