Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

tuples

c++14

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.

like image 216
quant Avatar asked Oct 25 '16 06:10

quant


People also ask

How do you find something in a tuple?

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.

How do you check if an input is in a tuple Python?

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.

How do you check if a string is present in a tuple?

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.

What keyword will be used to check if the value exist in a tuple?

We can test if an item exists in a tuple or not, using the keyword in .


2 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

like image 119
Piotr Skotnicki Avatar answered Nov 11 '22 10:11

Piotr Skotnicki


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

like image 23
krzaq Avatar answered Nov 11 '22 08:11

krzaq