Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a std::tuple in C++ 11 [duplicate]

Tags:

I have made the following tuple:

I want to know how should I iterate over it? There is tupl_size(), but reading the documentation, I didn't get how to utilize it. Also I have search SO, but questions seem to be around Boost::tuple .

auto some = make_tuple("I am good", 255, 2.1); 
like image 500
Mostafa Talebi Avatar asked Nov 13 '14 06:11

Mostafa Talebi


People also ask

How to iterate over tuple in c++?

So, we have two methods here, to iterate through the values of a tuple: Using Variadic Templates and metaprogramming (No use of std::apply). Using Variadic Templates and std::apply.

How do you iterate through a tuple element?

The basic idea is to turn tuples into a range with begin() and end() methods to provide iterators. The iterator itself returns a std::variant<...> which can then be visited using std::visit . Read-only access is also supported by passing a const std::tuple<>& to to_range() .

Is std :: tuple a container?

The new std::array and std::tuple containers provide developers with additional ways to manage structured data efficiently.

How do you iterate through a std queue?

Using std::queue In other words, std::queue is not meant to be iterated over. If you need to iterate over a std::queue , you can create a copy of it and remove items from the copy, one at a time, using the standard pop function after processing it.


1 Answers

template<class F, class...Ts, std::size_t...Is> void for_each_in_tuple(const std::tuple<Ts...> & tuple, F func, std::index_sequence<Is...>){     using expander = int[];     (void)expander { 0, ((void)func(std::get<Is>(tuple)), 0)... }; }  template<class F, class...Ts> void for_each_in_tuple(const std::tuple<Ts...> & tuple, F func){     for_each_in_tuple(tuple, func, std::make_index_sequence<sizeof...(Ts)>()); } 

Usage:

auto some = std::make_tuple("I am good", 255, 2.1); for_each_in_tuple(some, [](const auto &x) { std::cout << x << std::endl; }); 

Demo.

std::index_sequence and family are C++14 features, but they can be easily implemented in C++11 (there are many available on SO). Polymorphic lambdas are also C++14, but can be replaced with a custom-written functor.

like image 124
T.C. Avatar answered Oct 13 '22 01:10

T.C.