I want to write a function template that will generalize the following boolean function to any container of any class.
1 2 3 4 5 6 7 8
bool isOfCertainGroup (string personName, vector<Person> &person) {
for ( vector<Person>:: iterator it = person.begin (); it != person.end (); ++it )
{
if ((*it).name == personName)
returntrue;
}
returnfalse;
}
So here vector<Person> is just a special case of a specific container vector of a specific class Person. How do I write the template function? Am I doing something like template<template <class> class container, class T>? I'm quite lost.
Probably the best way is to make your function prototype similar to the STL algorithms. Instead of passing a class, they take iterators. I faced this problem, too, before I learned about STL algorithms, so when I tried to use templates, I made a huge friggin' mess.
You no need to write such a function because there is already such function in C++ named std::any_of. And it is already a template function.
For example
1 2 3 4 5
if ( std::any_of( Person.begin(), Person.end(),
[&personName]( const std::string &p ) { return ( p == personName ); } ) )
{
std::cout << "There is such a record in the vector\n";
}