c++ computing a new vector which has deltas from an existing vector

I'm working on learning C++ STL algorithms. I need help trying to find a function to create a vector of deltas from values in an existing vector. In other words:

  • delta0 = abs(original1 - original0)
  • delta1 = abs(original2 - original1)
  • and so on.

I'm looking for something concise, like R's "diff" function mentioned here: computing a new vector which has deltas from an existing vector

I found the transform function but it seemed to operate on a single element at a time. It didn't seem to allow parameters of iterator in the function supplied to transform so I was limited to the current element only. I'm trying to learn STL algorithms so I don't really need any libraries that may have "diff" implemented. I would just like to see a way to use STL functions to solve this if there is a concise way I'm not aware of.

Here is an example with the section in question commented:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = { 1, 2, 3, 4, 5 };
    vector<int> delta;

    //---------------------------------------
    // way to do this with STL algorithms?
    for (auto i = v.begin()+1; i != v.end(); i++) {
        delta.push_back(abs(*i - *(i - 1)));
    }
    //---------------------------------------
    for (int i : delta) {
        cout << i << " ";
    }
    return 0;
}

Answers


std::transform(std::next(v.begin()), v.end(),
               v.begin(), delta.begin(),
               [](int a, int b){ return std::abs(a - b); });

You simply missed the second version of transform. Take a look at it here.

See that code in action online!


Need Your Help

creating tabs using jquery

javascript jquery asp.net

I'm trying to create tabs on my Content Page, but it does not work for me.

How to get secure timer in project?

c# .net security c#-4.0 .net-security

In my C# project I want to set timer check validation my exe file and protect it. But when I want to check validation I must get timer from Bios timer or OS timer. Both of them can change by End us...