I'm annoyed that STL containers don't have a, well, contains()
method returning true
if the container contains an element, false
otherwise. So, I sat down and wrote this:
template <typename C, typename E>
inline bool contains(const C& container, const E& element) {
return container.find(element) != container.end();
}
which works well enough for sets and maps, but not for vectors. Or lists. How should I proceed? Should I write an additional
template <typename T>
inline bool contains(const vector<T>& container, const T& element) {
std::find(vector.begin(), vector.end(), item) != vector.end()
}
and more specific code for other containers? Should I instead settle on the sub-optimal use of iterators to check element-by-element? I would really much rather not do that... perhaps I'm not noticing some relevant STL functionality?
If you intend to use this function only on STL containers, and if you further have no need to process the iterator returned by
find
, then yes, I would suggest you to write specific code for these containers. It is the most effective you can do.The alternative would be to use metaprogramming and let the compiler determine whether the class contains a specific
find
function, but that would maybe be a bit overkill... Anyways, if want to go this way, you can read the recipes in this thread.