Consider the following toy code to determine whether a range contains an element:
template<typename Iter, typename T>
bool contains1(Iter begin, Iter end, const T& x)
{
for (; begin != end; ++begin)
{
if (*begin == x) return true;
}
return false;
}
(Yes I know, there are already perfectly fine algorithms in the standard library, that's not the point.)
How would I write the same thing with for_each
and a lambda? The following doesn't work...
template<typename Iter, typename T>
bool contains2(Iter begin, Iter end, const T& x)
{
std::for_each(begin, end, [&x](const T& y) {
if (x == y) return true;
});
return false;
}
...because that would only return from the lambda, not from the function.
Do I have to throw an exception to get out of the lambda? Again, there are probably a dozen better solutions to this specific problem that do not involve lambdas at all, but that's not what I'm asking for.