如何找到元组中是否存在元素?

时间:2016-10-25 06:44:23

标签: c++

假设我有std::tuple

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

现在我想找到func是否为lambda中的任何元素返回true,其中func是一些lambda,例如:

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

我该怎么做?请注意,Types...可能很大,因此我不想每次都迭代所有元素。

3 个答案:

答案 0 :(得分:5)

#include <tuple>

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

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

Image of dnn html module

答案 1 :(得分:2)

这是一个C ++ 14解决方案:

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

答案 2 :(得分:0)

这是一个有点复古的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;
}