user1444426
user1444426

Reputation: 635

Is it possible to rewrite this as a one liner?

This is actual code.Here I am calling for_each to carry out the function shown in sum.Can this be reduced to writing the function inside the for_each statement itself?

int S;
struct sum
{
 sum(int& v): value(v){}
 void operator()(int data)const {value+=(int)((data+(data%S==0?0:S))/S)+2;}
 int& value;
};
int main()
{
  int cnt=0;
  S=5;
  for_each(flights.begin(),flights.end(),sum(cnt));
  cout<<cnt-2;
  return 0;
}

Upvotes: 2

Views: 193

Answers (2)

hansmaad
hansmaad

Reputation: 18905

You could use std::accumulate from <numeric> which perfectly expresses your intent to build a sum.

int main()
{
    int flights[] = {1, 2, 3};
    int S = 5;
    std::cout << std::accumulate(
        begin(flights), end(flights), 0, 
        [S] (int sum, int data) { return sum + (int)((data+(data%S==0?0:S))/S)+2; })
        - 2;
}

Although you asked for a one liner, I prefer to give this non trivial lambda a name to increase readability.

int main()
{
    int flights[] = {1, 2, 3};
    auto theFooBarSum = [] (int sum, int data) 
        { return sum + (int)((data+(data%5==0?0:5))/5)+2; };
    int initialValue = 0;

    std::cout << std::accumulate(
        begin(flights), end(flights), initialValue , theFooBarSum) - 2;
}

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

In C++11, you can, using lambdas with a capture:

int main()
{
  int cnt = 0;
  S = 5;
  for_each(
    flights.begin(), flights.end(),
    [&] (int data) {
        cnt += (data + (data % S == 0 ? 0 : S)) / S + 2;
    });
  cout << cnt - 2;
  return 0;
}

The way this reads is: you have an anonymous function taking an int argument, which captures ([&]) the surrounding context by reference. Note that this is as efficient as your solution since the compiler effectively creates the structure from the lambda for you.

– As Navaz noted int he comments, the cast is actually unnecessary. Furthermore, C-style casts are generally seen as deprecated – use C++ casts instead.

Upvotes: 9

Related Questions