Gistrec

Возводим все в квадрат

Dec 13th, 2018
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <vector>
  5. #include <utility> // std::pair, std::get
  6.  
  7. /**
  8.  * Возводим все в квадрат
  9.  * vector, map, pair
  10.  */
  11.  
  12. template <class Type>
  13. Type Sqr(Type var) {
  14.     return var * var;
  15. }
  16.  
  17. template <class Type>
  18. std::vector<Type> Sqr(std::vector<Type> vec) {
  19.     for (auto &elem : vec) {
  20.         elem = Sqr(elem);
  21.     }
  22.     return vec;
  23. }
  24.  
  25. template <class First, class Second>
  26. std::pair<First, Second> Sqr(std::pair<First, Second> pair) {
  27.     std::get<0>(pair) = Sqr(std::get<0>(pair));
  28.     std::get<1>(pair) = Sqr(std::get<1>(pair));
  29.     return pair;
  30. }
  31.  
  32. template <class First, class Second>
  33. std::map<First, Second> Sqr(std::map<First, Second> map) {
  34.     for (auto &elem : map) {
  35.         elem.second = Sqr(elem.second);
  36.     }
  37.     return map;
  38. }
  39.  
  40. int main() {
  41.     std::vector<int> v = {1, 2, 3};
  42.     std::cout << "vector:";
  43.     for (int x : Sqr(v)) {
  44.         std::cout << ' ' << x;
  45.     }
  46.     std::cout << std::endl;
  47.  
  48.     std::map<int, std::pair<int, int>> map_of_pairs = {
  49.             {4, {2, 2}},
  50.             {7, {4, 3}}
  51.     };
  52.     std::cout << "map of pairs:" << std::endl;
  53.     for (const auto& x : Sqr(map_of_pairs)) {
  54.         std::cout << x.first << ' ' << x.second.first << ' ' << x.second.second << std::endl;
  55.     }
  56.  
  57.     return 0;
  58. }
Add Comment
Please, Sign In to add comment