0

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]);

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.