sunny
sunny

Reputation: 189

Using accumulate to calculate alternate sum

If I use the accumulate function in C++ like the below

 std::vector<int> v2{1, 2, 3, 4, 5};
 int sum = 0;
 std::cout << std::accumulate(v2.begin(), v2.end())

It will simply sum all the numbers. But I wanted to calculate 1-2+3-4+5
I was thinking of some way to accumulate 1,3,5 and 2,4 separately and then do it
But not sure how to achieve this using accumulate.

Upvotes: 3

Views: 1188

Answers (3)

catnip
catnip

Reputation: 25388

I wouldn't bother with std::accumulate at all here, it's not really suitable. Instead, just use two loops:

int result = 0;
size_t n = v2.size ();
for (size_t i = 0; i < n; i += 2)
    result  += v2 [i];
for (size_t i = 1; i < n; i += 2)
    result -= v2 [i];

Upvotes: 2

cigien
cigien

Reputation: 60218

I wanted to calculate 1-2+3-4+5

I was thinking of some way to accumulate 1,3,5 and 2,4 separately and then do it

This is a very good approach to the problem. The standard library doesn't have a stride view yet (though it does have drop), and with that you could write

int sum = accumulate(v2 | stride(2), 0) -
          accumulate(v2 | drop(1) | stride(2), 0);

You can do this with the range-V3 library until stride is added.

Upvotes: 1

Pepijn Kramer
Pepijn Kramer

Reputation: 12848

This is my quick solution :

int sign = -1; // start with minus first (e.g. 1-2)
std::vector<int> values{ 1, 2, 3, 4, 5 };

auto value = std::accumulate(values.begin(), values.end(), 0, [&sign](int total, int value)
{ 
    sign = -sign;  
    return total + (sign)*value;
});

Upvotes: 5

Related Questions