Advertisement
chevengur

СПРИНТ № 2 | Шаблоны функции | Урок 5: Универсальные функции вывода контейнеров 6/6

Oct 27th, 2023 (edited)
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. #include <map>
  5.  
  6. using namespace std;
  7.  
  8. template<typename key, typename value>
  9. void Print(ostream& out, const map<key, value>& kunteynir){
  10.     bool first_ap = true;
  11.  
  12.     for(const auto& [name, age]: kunteynir){
  13.         if(!first_ap){
  14.             cout << ", ";
  15.         }
  16.         first_ap = false;
  17.         out << "(" << name << ", " << age << ")";
  18.     }
  19. }
  20.  
  21. /*
  22. ИЛИ
  23.  
  24. template<typename key, typename value>
  25. ostream& operator<<(ostream& out, const pair<key, value>& kunteynir){
  26.     return out << "(" << kunteynir.first << ", " << kunteynir.second << ")";
  27. }
  28. */
  29.  
  30.  
  31. template<typename type>
  32. void Print(ostream& out, const type& kunteynir){
  33.     bool first_ap = true;
  34.    
  35.     for(const auto& kun: kunteynir){
  36.         if(!first_ap){
  37.             out << ", ";
  38.         }
  39.         first_ap = false;
  40.         out << kun;  
  41.     }
  42. }
  43.  
  44. template<typename type>
  45. ostream& operator<< (ostream& out, const set<type>kunteynir){
  46.     out << "{";
  47.     Print(out, kunteynir);
  48.     out << "}";
  49.     return out;
  50. }
  51.  
  52. template<typename type>
  53. ostream& operator<< (ostream& out, const vector<type>kunteynir){
  54.     out << "[";
  55.     Print(out, kunteynir);
  56.     out << "]";
  57.     return out;
  58. }
  59.  
  60. template<typename key, typename value>
  61. ostream& operator<< (ostream& out, const map<key, value>kunteynir){
  62.     out << "<";
  63.     Print(out, kunteynir);
  64.     out << ">";
  65.     return out;
  66. }
  67.  
  68.  
  69. int main() {
  70.     const vector<int> ages{10, 5, 2, 12};
  71.     const set<string> set_ages{"Белка", "Георгий", "Мурка", "Рюрик"};
  72.     const map<string, int> cat_ages = {
  73.     {"Мурка"s, 10},
  74.     {"Белка"s, 5},
  75.     {"Георгий"s, 2},
  76.     {"Рюрик"s, 12}
  77. };
  78.     cout << ages << endl;
  79.     cout << set_ages << endl;
  80.     cout << cat_ages << endl;
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement