quant
quant

Reputation: 23052

How can I find if an element exists in a tuple?

Suppose I have a std::tuple:

std::tuple<Types...> myTuple;
// fill myTuple with stuff

Now I want to find if func returns true for any element in the lambda, where func is some lambda, e.g.:

auto func = [](auto&& x) -> bool { return someOperation(x); }

How can I do this? Note that Types... may be large so I don't want to iterate over all elements every time.

Upvotes: 8

Views: 2580

Answers (3)

W.F.
W.F.

Reputation: 13988

And here's a little bit retro c++11 solution:

#include <iostream>
#include <tuple>

template <class Tuple, class Lambda>
bool any_of(Tuple &&tup, Lambda lambda, std::integral_constant<size_t, std::tuple_size<Tuple>::value> i) {
    return false;
}

template <class Tuple, class Lambda, class I = std::integral_constant<size_t, 0>>
bool any_of(Tuple &&tup, Lambda lambda, I i = {}) {
    return lambda(std::forward<typename std::tuple_element<i, Tuple>::type>(std::get<i>(tup))) ||
           any_of(std::forward<Tuple>(tup), lambda, std::integral_constant<size_t, i+1>{});
}

int main() {
   std::cout << any_of(std::forward_as_tuple(1, 2, 3, 4), [](int&& i) { return i == 2; }) << std::endl;
}

Upvotes: 0

krzaq
krzaq

Reputation: 16421

Here's a C++14 solution:

template <typename Tuple, typename Pred>
constexpr bool any_of_impl(Tuple const&, Pred&&, std::index_sequence<>) {
    return false;
}

template <typename Tuple, typename Pred, size_t first, size_t... is>
constexpr bool any_of_impl(Tuple const& t, Pred&& pred, std::index_sequence<first, is...>) {
    return pred(std::get<first>(t)) || any_of_impl(t, std::forward<Pred>(pred), std::index_sequence<is...>{});
}

template <typename... Elements, typename Pred, size_t... is>
constexpr bool any_of(std::tuple<Elements...> const& t, Pred&& pred) {
    return any_of_impl(t, std::forward<Pred>(pred), std::index_sequence_for<Elements...>{});
}

live demo

Upvotes: 2

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

#include <tuple>

std::tuple<int, char, double> myTuple{ 1, 'a', 3.14f };

bool result = std::apply([](auto&&... args) {
                           return (someOperation(decltype(args)(args)) || ...);
                         }
                       , myTuple);

DEMO

Upvotes: 5

Related Questions