Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Competency test question 2
- //
- //Provide a function receiving an integer (X) and a tuple (std::tuple<type1, type2, type3…>) into a tuple of vectors (std::tuple<std::vector,std::vector, std::vector, …> where each vector has X elements of each originally received in each tuple_element. E.g. for X=2 and the tuple {1, 1.0, ‘a’} , the result type is std::tuple<std::vector, std::vector, std::vector> and the values are: {{1, 1},{1.0, 1.0},{‘a’, ‘a’}}
- //
- // Gets the first value, makes a vector with it's x copies, makes a tuple
- // of it, and caoncats it with the tuple of vectors of rest of the values
- #include <iostream>
- #include <tuple>
- #include <vector>
- using namespace std;
- template < std::size_t... N , typename... T >
- auto tail_impl( std::index_sequence<N...> , std::tuple<T...> t ) {
- return std::make_tuple( std::get<N+1>(t)... );
- }
- template <class F, class... R >
- tuple<R...> tail( std::tuple<F,R...> t ) {
- return tail_impl( std::make_index_sequence<sizeof...(R)>() , t );
- }
- template<class... T>
- tuple<vector<T>...> func(int, tuple<T...>);
- template<class F, class... T>
- tuple<vector<F>,vector<T>...> func(int x, tuple<F,T...> t) {
- vector<F> f;
- F val = get<0>(t);
- for(int i=0;i<x;i++) {
- f.push_back(val);
- }
- return tuple_cat(make_tuple(f),func(x,tail(t)));
- }
- template<>
- tuple<> func<>(int x, tuple<> t) {
- return tuple<>();
- }
- template <class T>
- int tuple_length(T t) {
- return std::tuple_size<T>::value;
- }
- template<class T>
- void print_vec(vector<T> v) {
- for(auto& x:v) {
- cout << x << ' ';
- }
- cout << endl;
- }
- int main() {
- auto a = func(4,make_tuple(3,"er",5.45,'s'));
- cout << tuple_length(a) << endl;
- print_vec(get<0>(a));
- print_vec(get<1>(a));
- print_vec(get<2>(a));
- print_vec(get<3>(a));
- }
Add Comment
Please, Sign In to add comment