Webtm
Webtm

Reputation: 87

Add first + last elements, second + second to last elements etc. to a vector

This is what I have so far. And it seems to only add the first+last, second+last etc. I can't figure out how to make it add the second+second-to-last and so on. It is a dynamic vector, and iterators can't be used.

#include iostream
#include vector
using namespace std;

int main()
{
    vector<int> ack;
    int add;
    while(cin >> add)
    {
        ack.push_back(add);
    }

    for(size_t i = 0; i < ack.size(); i++)
    {
        cout << ack[i] + ack[ack.back() - 1] << endl;
    }
 }

Upvotes: 0

Views: 252

Answers (1)

Barry
Barry

Reputation: 302817

Your code is doubly wrong. ack.back() is just the value of the last element - that is unrelated to any operation you are trying to do. Also, ack.back() - 1 is not a function of your loop index - so ack[ack.back() - 1] is just some constant that you will add every time in the loop.

Since you want the "last - Nth" element every time, that implies that you need to subtract something from the size(). So what you want to do is:

for(size_t i = 0; i < ack.size(); i++)
{
    cout << ack[i] + ack[ack.size() - i - 1] << endl;
}

Upvotes: 2

Related Questions