gpt4 book ai didi

C++ Primer 第 5 版练习 3.24 - vector 中的迭代器

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:09 26 4
gpt4 key购买 nike

2014 年 9 月,我刚刚开始使用 Lippman、Lajoie & Moo 的 C++ Primer 第五版(第 5 次打印,2014 年 5 月)自学 C++。那本书中的一些练习我可以做,有些我不得不在这里寻求帮助,在这个我被困了好几天了。我搜索了谷歌、博客和其他论坛,一无所获,所以我向你求助。它是第 113 页的练习 3.24,它要求与第 105 页的练习 3.20 相同,但使用迭代器:

Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-to-last, and so on.

按照要求使用迭代器,我可以完成第一部分:

#include <iostream>
#include <vector>

using std::cin; using std::cout; using std::endl; using std::vector;

int main()
{
vector<int> lista;
int num_entra = 0;

while (cin >> num_entra)
lista.push_back(num_entra);


cout << "Sum of adjacent pairs: " << endl;
for (auto it = lista.begin(); it != lista.end() - 1; ++it)
{
*it += *(it + 1);
cout << *it << ' ';
}

return 0;
}

上面的代码按预期工作,但是我需要对第一个和最后一个、第二个和倒数第二个...等求和的部分有一个我无法解决的问题:

int main()
{
vector<int> lista;
int num_entra = 0;

while (cin >> num_entra)
lista.push_back(num_entra);


auto ult = lista.end();

cout << "Sum of the first and last elements until the center: " << endl;
for (auto it = lista.begin(); it != lista.end() - 1; ++it)
{
*it = *it + *(--ult);
cout << *it << ' ';
}

return 0;
}

如果用户输入 1 2 3 4 5 6,程序会按原样添加 1 + 6、2 + 5 和 3 + 4,
但随后它将最后一个结果 (7) 与 5 相加,然后与 6 相加,我似乎无法找到阻止这种行为的方法。我该怎么做才能让程序只显示每一对的总和,直到列表的中心?提前谢谢你。

最佳答案

一种方法是使用两个迭代器

auto front = lista.begin();  // start at front and increment
auto back = lista.end() - 1; // start at back and decrement
for (;
back > front; // stop when the iterators cross each other
++front, --back)
{
int total = *front + *back;
std::cout << total << ' ';
}

关于C++ Primer 第 5 版练习 3.24 - vector 中的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com