Sagar2018

q3.cpp

Mar 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. // Question 3
  2. // Provide a template function “get_vector”, similar to std::get, that given the type X as parameter, returns editable access to the vector of type X in a tuple of vectors.
  3.  
  4. #include <iostream>
  5. #include <tuple>
  6. #include <vector>
  7. #include <utility>
  8. #include <type_traits>
  9. #include <assert.h>
  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. void print_vec(const vector<T>& v) {
  25.     for(auto& x:v) {
  26.         cout << x << '\n';
  27.     }
  28.     cout << endl;
  29. }
  30.  
  31.  
  32. template<typename X, typename T>
  33. vector<X>& get_vector(T& t) {
  34.     return get<vector<X>>(t);
  35. }
  36.  
  37. int main( int argc, const char *argv[] ) {
  38.     auto a = vector<int>({4,5,3});
  39.     auto b = vector<char>({'s', 'a', 'g', 'a'});
  40.     auto c = vector<double>({3.232,32.3,2.33});
  41.     auto t = make_tuple(a,b,c);
  42.     vector<char>& f = get_vector<char>(t);
  43.     f.push_back('r');
  44.     print_vec(f);
  45.     print_vec(get<0>(tail(t)));
  46.     return 0;
  47. }
Add Comment
Please, Sign In to add comment