This C++ program demonstrates the count_if algorithm. The count_if takes three arguments – of which the first two are iterators to the beginning and end of the container and the third argument is predicate. The container used here is map which stores name of the companies and their revenue. The predicate checks for companies with annual revenue greater than $125 billion.
Here is the source code of the C++ program demonstrates the count_if algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to demonstrate count_if() algorithm
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <iomanip>
// Returns true for companies with revenue greater than $125 billion
bool fun(std::pair <std::string, int> p)
{
std::cout << std::setw(15) << std::left
<< p.first << std::setw(10)
<< p.second << std::endl;
if(p.second > 125)
return true;
else
return false;
}
int main()
{
std::map <std::string, int> m;
int c;
m.insert(std::pair <std::string, int>("IBM", 104));
m.insert(std::pair <std::string, int>("HP", 120));
m.insert(std::pair <std::string, int>("Verizon", 115));
m.insert(std::pair <std::string, int>("WalMart", 469));
m.insert(std::pair <std::string, int>("AT&T", 127));
std::cout << "Company\tRevene($ billion)" << std::endl;
std::cout << "-------\t-----------------" << std::endl;
c = count_if(m.begin(), m.end(), fun);
std::cout << "Number of companies = "
<< c << std::endl;
return 0;
}
$ a.out Company Revene($ billion) ------- ----------------- AT&T 127 HP 120 IBM 104 Verizon 115 WalMart 469 Number of companies = 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.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Programming Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Apply for Computer Science Internship
- Practice Programming MCQs