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.
Find the index of an element in tuple using index() Tuple provides a member function index() i.e. It returns the index for first occurrence of x in the tuple. Also, if element is not found in tuple then it will throw an exception ValueError.
Method #1: Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.
Method #1: Using loop This is a brute force method to perform this task. In this, we iterate through the tuple and check each element if it's our, if found we return True.
We can test if an item exists in a tuple or not, using the keyword in .
#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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With