This C++ program illustrates the use of greater predicate. The greater predicate is a binary function object which takes two parameters and returns true if first parameter is greater than the second parameter. We are using this predicate to compare the vectors lexicographically by using lexicographical_compare algorithm and passing greater as the fifth parameter.
Here is the source code of the C++ program demonstrates using greater predicate. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to illustrate the use of greater predicate
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
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;
}
int main()
{
std::vector <int> a(10), b(10), c(10);
bool result;
for (int i = 0; i < 10 ;i++)
{
a[i] = i + 1;
b[i] = i + 2;
}
std::cout << "a : ";
print(a);
std::cout << "b : ";
print(b);
std::cout << "c : ";
print(c);
// Comparing a and b lexicographically
result = std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), std::greater<int>());
if(result == true)
{
std::cout << "a is lexicographically greater than b."
<< std::endl;
}
else
{
std::cout << "a is lexicographically smaller than or equal to b."
<< std::endl;
}
// Comparing b and c lexicographically
result = std::lexicographical_compare(b.begin(), b.end(), c.begin(), c.end(), std::greater<int>());
if(result == true)
{
std::cout << "b is lexicographically greater than c."
<< std::endl;
}
else
{
std::cout << "b is lexicographically smaller than or equal to c."
<< std::endl;
}
}
$ a.out a : 1 2 3 4 5 6 7 8 9 10 b : 2 3 4 5 6 7 8 9 10 11 c : 0 0 0 0 0 0 0 0 0 0 a is lexicographically smaller than or equal to b. b is lexicographically greater than c.
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
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Computer Science Books