Advertisement
Alaricy

Тема9 Урок 5 6/6 универсальный вывод контейнеров

Oct 29th, 2022 (edited)
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. #include <map>
  5. using namespace std;
  6.  
  7. template <typename print>
  8. ostream& Print(ostream& out, const print& container){
  9.     bool isfirst=1;
  10.     for (const auto& element : container) {
  11.     if (isfirst)  out << ""s;
  12.     else out << ", "s;
  13.     isfirst=0;
  14.     out << element << ""s;
  15.     }
  16.   return out;
  17. }
  18.  
  19. template <typename invect>
  20. ostream& operator<<(ostream& out, const vector<invect>& container) {
  21. out<<"[";
  22. Print(out, container);
  23. out<<"]";
  24. return out;
  25. }
  26.  
  27. template <typename inset>
  28. ostream& operator<<(ostream& out, const set<inset>& container) {
  29. out<<"{";
  30. Print(out, container);
  31. out<<"}";
  32.     return out;    
  33. }
  34.  
  35. template <typename Key, typename Value>
  36. ostream& operator<<(ostream& out, const map<Key, Value>& container) {
  37. out<<"<";
  38. bool isfirst=1;
  39. for (const auto& [key, value] : container){
  40.     if (isfirst)  out << ""s;
  41.     else out << ", "s;
  42.     isfirst=0;
  43. out<<"("<<key<<", "<<value<<")";
  44. }
  45. out<<">";
  46.     return out;  
  47. }
  48.  
  49. int main() {
  50.     const set<string> cats = {"Мурка"s, "Белка"s, "Георгий"s, "Рюрик"s};
  51. cout << cats << endl;
  52. const vector<int> ages = {10, 5, 2, 12};
  53. cout << ages << endl;
  54. const map<string, int> cat_ages = {
  55.     {"Мурка"s, 10},
  56.     {"Белка"s, 5},
  57.     {"Георгий"s, 2},
  58.     {"Рюрик"s, 12}
  59. };
  60. cout << cat_ages << endl;
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement