第一个练习3.21:使用迭代器重做练习3.20,将每队相邻整数的和输出
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> text;
int x;
while(cin >> x)
{
text.push_back(x);
}
for (auto it = text.begin() + 1; it != text.end(); ++it)
{
auto c = *it + *(it - 1);
cout << c << endl;
}
return 0;
}
第二个练习3.24:使用迭代器,先输出第一个元素和最后一个元素的和,接着输出第二个元素和倒数第二个元素的和,以此类推
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> text;
int x;
while(cin >> x)
{
text.push_back(x);
}
for (auto it = text.begin(); it != text.end(); ++it)
{
auto c = *it + *(text.end() - *it);
cout << c << endl;
}
return 0;
}
思路代码还有许多不足,还请各位多多指教!
本文使用C++ Primer第五版中的迭代器来解决练习3.21和3.24。练习3.21涉及计算相邻整数的和,而练习3.24则要求输出序列中对应位置元素的和,如首尾元素、次首次尾元素等。代码实现仍有提升空间,欢迎读者提供宝贵建议。
2万+

被折叠的 条评论
为什么被折叠?



