jack06215

[tutorial] print collection using std::copy()

Jul 12th, 2020 (edited)
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm> // for copy
  3. #include <iterator> // for ostream_iterator
  4. #include <vector>
  5. #include <functional>
  6.  
  7. class Employee {
  8. public:
  9.     Employee(const std::string _name, const std::string _last, const int _sal):
  10.         name(_name),
  11.         lastname(_last),
  12.         salary(_sal ) {}
  13.  
  14.     friend std::ostream& operator<<(std::ostream&os,  const Employee& obj) {
  15.         return os << obj.name << " "<< obj.salary;
  16.     }
  17.  
  18. private:
  19.     std::string name;
  20.     std::string lastname;
  21.     int salary;
  22. };
  23.  
  24. int main()
  25. {
  26.     /* Set up vector to hold some number */
  27.     std::vector<int> col{ 23, 23, 37, 42, 23, 23, 37 };
  28.  
  29.     /* Set up vector to hold chars a-z */
  30.     std::vector<char> path;
  31.     for (int ch = 'a'; ch <= 'z'; ++ch)
  32.         path.push_back(ch);
  33.  
  34.     /* Set up vector to hold employer detail */
  35.     std::vector<Employee> staff {
  36.         {"Murrary", "Steve", 1000 },
  37.         {"Dave", "Ark", 2000 },
  38.         {"Kate", "Greg", 2000 },
  39.         {"John", "Smith", 1000 },
  40.         {"Jack", "Cho", 2000 }
  41.     };
  42.  
  43.     std::copy(col.begin(), col.end(), std::ostream_iterator<int>(std::cout, " "));
  44.     std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, "\t"));
  45.     std::copy(staff.begin(), staff.end(), std::ostream_iterator<Employee>( std::cout, "\n"));
  46.     return 0;
  47. }
Add Comment
Please, Sign In to add comment