#include <iostream>
#include <vector>
using namespace std;
int main()
{
int typedNos;
if (cin >> typedNos)
{
vector <int> inputNos{ typedNos };
while (cin >> typedNos)
{
inputNos.push_back(typedNos);
}
for (decltype (inputNos.size()) n = 1; n < inputNos.size(); ++n)
{
cout << inputNos[0] + inputNos[1] << '\t' << inputNos[(2 * n) - 1]
+ inputNos[(2 * n)] << endl;
return 0;
}
}
else
{
cerr << " Wrong input type or no input was typed!" << endl;
//return -1;
}
}
一切正常,直到到达for循环中的输出语句为止。向量的前两对元素被手动添加为零。其余的将自动添加。但这仅适用于第一对。
因此,例如,输入:
1 2 3 4 5。
将为您提供以下输出:
3 5。
而不是3 5 7 9。
这是我遇到的问题。我已经看到了解决此问题的其他方法,但我的问题是为什么序列2n(偶数位置)和2n-1(奇数位置)不适用于整个矢量?请记住,这个问题不允许我使用迭代器。谢谢。
最佳答案
问题出在您的for-loop
上。在循环内使用return
仍将从当前函数退出。您当前的函数是main
,因此该程序结束。
我不确定您为什么认为需要2 * n
。似乎您要遍历每个对象,而不是第二个对象。
for (std::size_t n = 1; n < inputNos.size(); ++n) {
std::cout << inputNos[n] + inputNos[n-1] << '\t';
}
std::cout << std::endl;
关于c++ - 在不使用迭代器的情况下,将 vector 中的整数相加,第一个和第二个元素的和为to,依此类推,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53670012/