How do I know if an element exists in a tuple?

Suppose I have std::tuple :

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

Now I want to find if func returns true for any element in lambda, where func is some lambda, for example:

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

How can i do this? Please note that Types... can be large, so I don’t want to iterate over every element every time.

+7
c ++
source share
3 answers
 #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

+4
source share

Here's the 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 demonstration

+2
source share

And here is a bit of retro C ++ 11:

 #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; } 
0
source share

All Articles