Advertisement
aircampro

tuple & ties

Jun 15th, 2021
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. // Demonstration of tuple and ties on CM c++17
  2. //
  3. // g++-7 -std=c++17 tuple.cpp -o tuple
  4. //
  5. #include <iostream>
  6. #include <string>
  7. #include <tuple>
  8.  
  9. // function returns a tuple
  10. // a neat way of having const as a string - number union
  11. auto get_mark() {
  12.     return std::make_tuple("mark", 42);
  13. }
  14. auto get_nick() {
  15.     return std::make_tuple("nick", 45);
  16. }
  17.  
  18. main()
  19. {
  20.  
  21. // this time we list each item of the tuple returned
  22. auto t = get_mark();
  23. std::cout << std::get<0>(t) << std::endl;
  24. std::cout << std::get<1>(t) << std::endl;
  25.  
  26. auto u = get_nick();
  27. std::cout << std::get<0>(u) << std::endl;
  28. std::cout << std::get<1>(u) << std::endl;
  29.  
  30. // here we use tie and return the tuple to the tie
  31. std::string name;
  32. int age;
  33.  
  34. std::tie(name, age) = get_mark();
  35. std::cout << name << " is " << age << std::endl;
  36. std::tie(name, age) = get_nick();
  37. std::cout << name << " is " << age << std::endl;
  38.  
  39. // this time we auto return the tuple to name1 and age1
  40. auto [name1, age1] = get_mark();
  41. std::cout << name1 << " is " << age1 << std::endl;
  42. auto [name2, age2] = get_nick();
  43. std::cout << name2 << " is " << age2 << std::endl;
  44.  
  45. // this time we tie with the tuple and change its values
  46. auto t4 = std::make_tuple(10, 20);
  47. auto& [first, second] = t4;
  48. first += 1;
  49. second = 35;
  50. std::cout << "value is now " << std::get<0>(t4) << " second is new " << std::get<1>(t4) << std::endl;
  51.  
  52. }
  53.  
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement