Home > Net >  Functional-Style Programming in C
Functional-Style Programming in C

Time:11-06

Consider a few vectors v1,v2,v3 to which you need to apply one function (for example clear()).

vector <int> v1;
vector <int> v2;
vector <int> v3;

v1.clear();
v2.clear();
v3.clear();

Can I do it in one line? So I need something like that

someHOF(clear(), ls[v1, v2, v3]);

CodePudding user response:

Two lines:

for (auto v : {&v1, &v2, &v3})
    v->clear();

You could also make a function for this, but I don't see any benefit in doing so. And calling the function becomes complicated if the method you call is overloaded.

template <typename T, typename ...P>
void apply(T func, P &&... targets)
{
    (void((std::forward<P>(targets).*func)()), ...);
}

int main()
{
    std::vector<int> v1, v2, v3;
    apply(&std::vector<int>::clear, v1, v2, v3);
}

CodePudding user response:

You could use std::for_each from the algorithms library along with a lambda. This really doesn't improve on HolyBlackCat's initial suggestion, though.

#include <vector>
#include <algorithm>

int main() {
    using vec = std::vector<int>;

    vec v1 { 2, 3, 4 };
    vec v2 { 5, 6, 7 };
    vec v3 { 8, 9 };

    std::vector<vec*> v4 { &v1, &v2, &v3 };

    std::for_each(v4.begin(), v4.end(), [](auto &i){i->clear();});

    return 0;
}
  • Related