This C++ program demonstrates the max_element algorithm on a container. The max_element() function has two overloaded forms – one with a compare predicate as the third parameter and another without it. The program demonstrates both of the overloaded forms where one prints the element with maximum value in a vector and another using a compare function to find the pair element with maximum value in a map. The compare function compares the two pairs on the basis of their second arguments.
Here is the source code of the C++ program which demonstrates the max_element algorithm on a container. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to demonstrate the max_element() algorithm on a container
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
bool compare(std::pair <std::string, int> p, std::pair <std::string, int> q )
{
return p.second < q.second;
}
void print(const std::vector <int>& v)
{
std::vector <int>::const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
void fun(std::pair <std::string, int> p)
{
std::cout << p.first << "\t" << p.second << std::endl;
}
int main()
{
int arr[] = {10, 20, 30, 50, 40, 100, 70, 60, 80, 90};
std::vector <int> v(arr, arr + sizeof(arr)/sizeof(int));
std::map <std::string, int> marks;
std::pair <std::string, int> max;
marks["Alice"] = 60;
marks["Annie"] = 99;
marks["Harry"] = 90;
marks["Garry"] = 80;
std::cout << "max_element() without predicate " << std::endl;
std::cout << "Vector : ";
print(v);
std::cout << "Maximum element = "
<< *std::max_element(v.begin(), v.end())
<< std::endl;
std::cout << "\nmax_element() with predicate" << std::endl;
std::cout << "Name\tMarks" << std::endl;
for_each(marks.begin(), marks.end(), fun);
max = (*std::max_element(marks.begin(), marks.end(), compare));
std::cout << "Person with maximum marks = " << max.first
<< ", Marks = " << max.second << std::endl;
}
$ a.out max_element() without predicate Vector : 10 20 30 50 40 100 70 60 80 90 Maximum element = 100 max_element() with predicate Name Marks Alice 60 Annie 99 Garry 80 Harry 90 Person with maximum marks = Annie, Marks = 99
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Computer Science MCQs
- Apply for C++ Internship
- Apply for Computer Science Internship
- Check Computer Science Books
- Check Programming Books