Use iterators and algorithms to possibly make this code a bit tidier

(also, the code executed once the element was found was split half
inside the loop and half after it - now put it all together after the
find operation)

I'm a bit concerned that this code is rather untested (commenting out
this whole function and running check-clang doesn't fail any tests)...

And I wish I had polymorphic lambdas.