简体   繁体   English

迭代器算法

[英]Iterator arithmetic

I'm working right now with iterators arithmetic operations and stack on small problem . 我现在正在使用iterators 算术运算,并在小问题上进行堆栈。
I need to make a Sum of first and last element of vector<int> followed by second and last element of vector<int> , third and last element of vector<int> 我需要的第一和最后一个元素的总和 vector<int> ,随后的第二和最后一个元素vector<int>第三和最后一个元素vector<int>
Example: 例:
Input numbers by user 按用户输入数字
1 2 3 4 5 6 7 8 9
Output should be 输出应为
10 11 12 13 14 15 16 17
In general the code should do addition like that 一般来说,代码应该像这样做加法
1+9 2+9 3+9 4+9 5+9 6+9 7+9 ......

So basically i need the actual code for this arithmetic operation using iterator with member functions *.begin() , *.end() only ! 所以基本上我需要实际的代码,本次运算使用iterator与成员函数*.begin() , *.end() I've try many ways but nothing coming in my head how to do this operation only with .begin() and .end() . 我已经尝试了许多方法,但是仅使用.begin().end()如何进行此操作就没什么用。 I found other member functions but this functions is explained in STD library, not in basic knowledge level. 我发现了其他成员函数,但是此函数在STD库中进行了说明,而不是在基础知识级别中进行了说明。 So i need help to make code with only begin() and end() member functions if possible. 因此,如果可能的话,我需要帮助使代码仅具有begin()end()成员函数。

Code i got so far 我到目前为止的代码

int main()
{  

vector<int> numset;
int num_input;
auto beg=numset.begin(), end=numset.end();
while (cin>>num_input)
{
    numset.push_back(num_input);
}
for (auto it = numset.begin()+1; it !=numset.end(); ++it)
{
    // *it=*it+1+nuset.end(); -- Wrong  X
            // *it+=(end-beg)/2;      -- Totally wrong(and totally stupid) X
            // *it + numset.back()   -- can't use other member functions X 
    //////// I've stack here dont know what code need //////

              cout<<*it<<endl;    
}

Thank you for your time. 感谢您的时间。

The operation you perform is *it+*(it-1) . 您执行的操作是*it+*(it-1) (It might help to add more parentheses and spaces in your code.) That adds two adjacent elements from the sequence. (这可能有助于在代码中添加更多的括号和空格。)这将在序列中添加两个相邻的元素。

The last element in the sequence is numset.back() . 序列中的最后一个元素是numset.back() So try *it + numset.back() instead. 因此,请尝试*it + numset.back() And there's no need to start with the second element, since you do want to print the sum of the first and last elements. 无需从第二个元素开始,因为您确实想打印第一个和最后一个元素的总和。 If you don't want to print the sum of the last element with itself, you should stop at end() - 1 , though. 如果您不想与自己一起打印最后一个元素的总和,则应在end() - 1处停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM