by kleiba · 15y ago · 0 comments
auto i = find_if( begin(v), end(v), [=](int i) { return i > x && i < y; } );
This is the improved version by the way, but I'm not sure if a loop wouldn't be more readable for such a straight-forward problem. Plus I can't help but think that C++ will probably never win a beauty contest.Let's look at the equivalent C++98 loop:
int i = -1;
for(std::vector<int>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
if(*iter > x && *iter < y)
{
i = *iter;
break;
}
}
It's not only much more verbose, but the types need to be expressly written, and what's going on isn't immediately obvious from the function name.No, C++ will never win a beauty contest (I'd vote for D or Haskell personally), but it's great for expressibility, and the new C++11 changes make things more concise.
When you compare the new code to the C++98 one, it looks like a great improvement. But isn't that because C++98 simply sucked even more? As you say, when you compare it to languages like Haskell, even the new C++11 leaves something to be desired.
template <typename A, typename B>
struct between_ {
A a; B b;
between_(A const & a, B const & b) : a(a), b(b) {}
template <typename T>
bool operator()(T const & t) const { return a < t && t < b; }
};
template <typename A, typename B>
between_<A, B> between(A const & a, B const & b) {
return between_<A, B>(a, b);
}
// ...
auto i = find_if(begin(v), end(v), between(x, y));
Verbose? Admittedly. Except maybe for the point of use, i.e. the last line. Which, I think, helps a lot anyway.