Sagar2018

q2.cpp

Mar 20th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. // Competency test question 2
  2. //
  3. //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’}}
  4. //
  5. // Gets the first value, makes a vector with it's x copies, makes a tuple
  6. // of it, and caoncats it with the tuple of vectors of rest of the values
  7. #include <iostream>
  8. #include <tuple>
  9. #include <vector>
  10.  
  11. using namespace std;
  12.  
  13. template < std::size_t... N , typename... T >
  14. auto tail_impl( std::index_sequence<N...> , std::tuple<T...> t ) {
  15.    return  std::make_tuple( std::get<N+1>(t)... );
  16. }
  17.  
  18. template <class F, class... R >
  19. tuple<R...> tail( std::tuple<F,R...> t ) {
  20.    return  tail_impl( std::make_index_sequence<sizeof...(R)>() , t );
  21. }
  22.  
  23. template<class... T>
  24. tuple<vector<T>...> func(int, tuple<T...>);
  25.  
  26. template<class F, class... T>
  27. tuple<vector<F>,vector<T>...> func(int x, tuple<F,T...> t) {
  28.     vector<F> f;
  29.     F val = get<0>(t);
  30.     for(int i=0;i<x;i++) {
  31.         f.push_back(val);
  32.     }
  33.     return tuple_cat(make_tuple(f),func(x,tail(t)));
  34. }
  35.  
  36. template<>
  37. tuple<> func<>(int x, tuple<> t) {
  38.     return tuple<>();
  39. }
  40.  
  41. template <class T>
  42. int tuple_length(T t) {
  43.     return std::tuple_size<T>::value;
  44. }
  45.  
  46. template<class T>
  47. void print_vec(vector<T> v) {
  48.     for(auto& x:v) {
  49.         cout << x << ' ';
  50.     }
  51.     cout << endl;
  52. }
  53.  
  54. int main() {
  55.     auto a = func(4,make_tuple(3,"er",5.45,'s'));
  56.     cout << tuple_length(a) << endl;
  57.     print_vec(get<0>(a));
  58.     print_vec(get<1>(a));
  59.     print_vec(get<2>(a));
  60.     print_vec(get<3>(a));
  61. }
Add Comment
Please, Sign In to add comment