This is what I have now:
template<template<typename T> class container, typename T>
inline bool contains( const container<T> &cont, const T &element )
{
if( cont.size() == 0 )
return false;
return( std::find(cont.begin(), cont.end(), element) != cont.end() );
}
An I’d like to call it like so:
std::vector<string> stringvector;
contains( stringvector, "somestring" );
I believe this should be possible, but everything I’ve tried throws up a different error. Any help is appreciated. Thanks!
UPDATE: Thanks for all the answers already, I was looking too far, but I’m still having problems:
template<class container_type, typename T>
inline bool contains(const container_type& c, const T& e)
{
return !(c.size() && std::find(c.begin(),c.end(),e)!=c.end());
}
int main(int argc, char *argv[])
{
vector<string> stringvector;
stringvector.push_back("hello");
cout << contains( stringvector, string("hello") );
return 0;
}
fails to compile, even without the explicit `string´ constructor:
error: no matching function for call to 'find(std::vector<std::basic_string<char> >::const_iterator, std::vector<std::basic_string<char> >::const_iterator, const std::basic_string<char>&)'
STL containers take two arguments, one for the contained type and another for the allocator that describes how to obtain memory.
Try this:
However, this is really a good example of why you should avoid parameterizing algorithms on containers at all. It’s best to follow the pattern of
<algorithm>and only specify iterator type parameters.If you must ask for a container, don’t bother to specify what the container looks like. Just assume it has the interface you want. This is the easiest thing for you, and the most flexible thing for the user.