[英]Add the sum of integers located in a vector without using iterators, the sum is to for the first and second element and so forth
#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;
}
}
Everything works fine till the output statement in the for loop is reached. 一切正常,直到到达for循环中的输出语句为止。 The first two pairs of the vector's elements are manually added to account for zero. 向量的前两对元素会手动添加为零。 The rest are to be added automatically. 其余的将自动添加。 But this only works for the first pair. 但这仅适用于第一对。
So, for example, an input of: 因此,例如,输入:
1 2 3 4 5. 1 2 3 4 5。
Will give you an output of: 将为您提供以下输出:
3 5. 3 5。
Instead of 3 5 7 9. 而不是3 5 7 9。
This is where I have an issue. 这是我遇到的问题。 I have seen other methods of solving this problem but my question is why the sequence 2n (even positions) and 2n-1 (odd positions) do not work for the entire vector? 我已经看到了解决此问题的其他方法,但我的问题是为什么序列2n(偶数位置)和2n-1(奇数位置)不适用于整个矢量? Remember this question does not allow me to use iterators. 请记住,这个问题不允许我使用迭代器。 Thanks. 谢谢。
The problem lies in your for-loop
. 问题出在您的for-loop
。 Using return
inside a loop will still exit from the current function. 在循环内使用return
仍将从当前函数退出。 Your current function is main
, so this ends the program. 您当前的函数是main
,因此该程序结束。
I'm not really sure why you think you need 2 * n
. 我不确定您为什么认为需要2 * n
。 It seems you want to iterate over every object, not every second one. 似乎您要遍历每个对象,而不是第二个对象。
for (std::size_t n = 1; n < inputNos.size(); ++n) {
std::cout << inputNos[n] + inputNos[n-1] << '\t';
}
std::cout << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.