5.15
(a) for (int ix = 0; ix != sz; ++ix) { /* ... */ }
if (ix != sz) //ix是局部变量,这一句中没有定义
// . . .
(b) int ix;
for (ix != sz; ++ix) { /* ... */ }//for中缺少一个语句
(c) for (int ix = 0; ix != sz; ++ix, ++sz) { /*...*/ }//无限循环
改正:
(a) int ix;
for (ix = 0; ix != sz; ++ix) { /* ... */ }
if (ix != sz)
// . . .
(b) int ix;
for (; ix != sz; ++ix) { /* ... */ }
(c) for (int ix = 0; ix != sz; ++ix) { /*...*/ }
5.16
如果只能使用一种的话,我更希望使用for 因为for中,可以定义的语句更多,可以定义局部变量等。
5.17
#include <iostream>
#include <vector>
using namespace std;
bool is_prefix(vector<int> const& lhs, vector<int> const& rhs)
{
if(lhs.size() > rhs.size())
return is_prefix(rhs, lhs);
for(unsigned i = 0; i != lhs.size(); ++i)
if(lhs[i] != rhs[i]) return false;
return true;
}
int main()
{
vector<int> l{ 0, 1, 1, 2 };
vector<int> r{ 0, 1, 1, 2, 3, 5, 8 };
cout << (is_prefix(r, l) ? "yes\n" : "no\n");
return 0;
}