Users Online
· Guests Online: 93
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
Map Elements using for_each Algorithm in C++
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.
-
/*
-
* C++ Program to Print map using for_each algorithm
-
*/
-
#include <iostream>
-
#include <algorithm>
-
#include <string>
-
#include <map>
-
-
class X {
-
public:
-
void operator() (std::pair <int, std::string> p){
-
std::cout << p.first << "\t" << p.second << std::endl;
-
}
-
};
-
-
int main()
-
{
-
X x;
-
std::map <int, std::string> people;
-
people.insert(std::pair <int, std::string>(1, "Roger Federer"));
-
people.insert(std::pair <int, std::string>(2, "Rafael Nadal"));
-
people.insert(std::pair <int, std::string>(3, "Andy Murray"));
-
people.insert(std::pair <int, std::string>(4, "Novak Djokovic"));
-
-
std::cout << "Id\tPlayer Name " << std::endl
-
<< "--\t------------" << std::endl;
-
for_each(people.begin(), people.end(), x);
-
return 0;
-
}
$ a.out Id Player Name -- ------------ 1 Roger Federer 2 Rafael Nadal 3 Andy Murray 4 Novak Djokovic
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.