This C++ program demonstrates the remove_if() algorithm. The program creates a vector of strings and removes elements whose first letter is ‘A’ using predicate which is passed as a parameter to the remove_if algorithm which removes elements for which the predicate returns true.
Here is the source code of the C++ program which demonstrates the remove_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 remove_if algorithm
*/
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
typedef std::vector<std::string>::iterator iterator;
struct startsWithA : public std::unary_function<std::string, bool> {
bool operator() (std::string s)
{
if(s[0] == 'A')
{
return true;
}
else
return false;
}
};
void print(iterator b, iterator e)
{
iterator i;
for(i = b; i != e; i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
int main()
{
startsWithA s;
std::vector<std::string> v;
v.push_back("China");
v.push_back("India");
v.push_back("Atlanta");
v.push_back("Bolivia");
v.push_back("Australia");
v.push_back("Pakistan");
std::cout << "Vector : ";
print(v.begin(), v.end());
iterator i = remove_if(v.begin(), v.end(), s);
std::cout << "Vector : ";
print(v.begin(), i);
}
$ a.out
Vector : China India Atlanta Bolivia Australia Pakistan
Remove countries starting with 'A'
Vector : China India Bolivia Pakistan
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 C++ Internship
- Check Computer Science Books
- Check Programming Books
- Check C++ Books
- Practice Computer Science MCQs