Map Elements using for_each Algorithm in C++

«
»
This C++ program prints elements of map using for_each algorithm. The for_each function takes three parameters – iterator to the beginning of the container, the iterator to the end of the container and a function or function object of class X. A function object is a programming construct allowing an object to be invoked or called as if it were an ordinary function. The class X has an operator() which allows the for_each to execute the code inside it.

Here is the source code of the C++ program prints elements of map using for_each algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Print map using for_each algorithm
  3.  */ 
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <string>
  7. #include <map>
  8.  
  9. class X {
  10.     public:
  11.         void operator() (std::pair <int, std::string> p){
  12.             std::cout << p.first << "\t" << p.second << std::endl;
  13.         }
  14. };
  15.  
  16. int main()  
  17. {
  18.     X x;
  19.     std::map <int, std::string> people;
  20.     people.insert(std::pair <int, std::string>(1, "Roger Federer"));
  21.     people.insert(std::pair <int, std::string>(2, "Rafael Nadal"));
  22.     people.insert(std::pair <int, std::string>(3, "Andy Murray"));
  23.     people.insert(std::pair <int, std::string>(4, "Novak Djokovic"));
  24.  
  25.     std::cout << "Id\tPlayer Name " << std::endl
  26.               << "--\t------------" << std::endl;
  27.     for_each(people.begin(), people.end(), x);
  28.     return 0;
  29. }

$ a.out
Id      Player Name
--      ------------
1       Roger Federer
2       Rafael Nadal
3       Andy Murray
4       Novak Djokovic

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.