This C++ program demonstrates the min_element algorithm on a container. The min_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 minimum value in a vector and another using a compare function to find the pair element with minimum 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 min_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 min_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[] = {40, 80, 50, 30, 10, 70, 60, 100, 20, 90};
std::vector <int> v(arr, arr + sizeof(arr)/sizeof(int));
std::map <std::string, int> rank;
std::pair <std::string, int> min;
rank["John"] = 10;
rank["Chris"] = 5;
rank["Mark"] = 2;
rank["Henry"] = 7;
std::cout << "min_element() without predicate " << std::endl;
std::cout << "Vector : ";
print(v);
std::cout << "Minimum element = "
<< *std::min_element(v.begin(), v.end())
<< std::endl;
std::cout << "\nmin_element() with predicate" << std::endl;
std::cout << "Name\tMarks" << std::endl;
for_each(rank.begin(), rank.end(), fun);
min = (*std::min_element(rank.begin(), rank.end(), compare));
std::cout << "Person with best rank = " << min.first
<< ", Rank = " << min.second << std::endl;
}
$ a.out min_element() without predicate Vector : 40 80 50 30 10 70 60 100 20 90 Minimum element = 10 min_element() with predicate Name Marks Chris 5 Henry 7 John 10 Mark 2 Person with best rank = Mark, Rank = 2
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:
- Apply for Computer Science Internship
- Check C++ Books
- Apply for C++ Internship
- Check Computer Science Books
- Check Programming Books