template with containers

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)
      return true;
  }
  return false;
}


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.
Last edited on
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.
1
2
3
4
5
template<typename InIter>
bool isOfCertainGroup(std::string personName, InIter curr, InIter end){
   for(; curr!= end; ++curr) 
  //etc.
}
Am I doing something like template<template <class> class container, class T>?

no, because vector has more than one template parameter.

Iterators work best, but if you really want to pass a container, then template on the container's entire type:

1
2
3
4
5
template<typename Container>
bool isOfCertainGroup(const std::string& personName, const Container& person)
{
    return find_if(person.begin(), person.end(), [&](const Person& p){ return p.name == personName;}) != person.end();
}
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";
}

Last edited on
Topic archived. No new replies allowed.