c++ - template syntax for containers -
this 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 call so:
std::vector<string> stringvector; contains( stringvector, "somestring" ); i believe should possible, i've tried throws different error. appreciated. thanks!
update: answers already, looking far, 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 compile, without explicit `string´ constructor:
error: no matching function call '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, 1 contained type , allocator describes how obtain memory.
try this:
template<template<typename t, typename alloc> class container, typename t, typename alloc> inline bool contains( const container<t, alloc > &cont, const t &element ) however, example of why should avoid parameterizing algorithms on containers @ all. it's best follow pattern of <algorithm> , specify iterator type parameters.
template< typename iter, typename t > inline bool contains( iter first, iter last, const t &element ) { return std::find( first, last, element ) != last; } if must ask container, don't bother specify container looks like. assume has interface want. easiest thing you, , flexible thing user.
template< typename cont, typename t > inline bool contains( cont const &cont, t const &element ) { return std::find( cont.begin(), cont.end(), element ) != cont.end(); }
Comments
Post a Comment