Search code examples
c++lambdafunctor

Functors and iteration trough vector


I'm trying to get into 'modern' C++, so I'm trying to learn how to properly use functors, and, subsequently, lambdas. I think I've understood basic principle behind it, but I'm having trouble to understand how to acquire any element from a vector that is passed to my algorithm. So, let's say I wish to create a Fibonacci sequence of length N...

struct Adder {
    int operator()(int a, int b) {return a+b;}
};
const int N = 10;

int main() {

    std::vector<int> vec = {0, 1};
    vec.resize(N);

    //Old Way
    for(int i = 2; i < vec.size(); i++) {
        vec[i] = vec[i-1] + vec[i-2];
    }

    std::transform(vec.begin(), vec.end(), vec.begin(), [](int i){return i*3;});    //single operator given to function, works

//    std::transform(vec.begin()+2, vec.end(), vec.begin(), /*here two calls are needed , for a and b operators*/);

    return 0;
}

Basically my question is how to activate functor defined in struct Adder? What is the proper way to pass two operators to him?


Solution

  • Adder::operator() should be const. And your Adder functor is unnecessary. Just use std::plus<>.

    Since C++17, we have the transform overload that accepts two sequences. So we can do: (you can use Adder{} in place of std::plus<>{} if you want)

    std::transform(vec.begin(), vec.end() - 2, vec.begin() + 1, vec.begin() + 2, std::plus<>{});
    

    Minimal example: (live demo)

    #include <algorithm>
    #include <iostream>
    #include <vector>
    
    constexpr int N = 10;
    
    int main()
    {
        std::vector<int> vec{0, 1};
        vec.resize(N);
    
        std::transform(vec.begin(), vec.end() - 2, vec.begin() + 1, vec.begin() + 2, std::plus<>{});
    
        for (int x : vec)
            std::cout << x << " ";
        std::cout << "\n";
    }