Search code examples
c++vectorpredicatefunctor

Use Functor / Predicate to find the first element smaller than its predecessor in vector


currently I am trying to use function objects to find the first element that is smaller than the previous element in a vector. For example I have vector v and its contents are { 25, 30, 10, 40}; I tried toying with functors and with the algorithm library, but I can't get a correct result. My attempt was:

auto target = find_if( v.begin( ), v.end( ), &greaterneighbour );
if ( target != v.end( ) )
    cout << target << endl;

The functor I tried to implement however was incorrect and only worked with pre-set elements (like comparing each element with 4). My question is how can I use functors to compare two elements of a vector.


Solution

  • You can use std::adjacent_find() for that.

    auto iter = std::adjacent_find(begin(v), end(v), [](const auto& a, const auto& b) { return a < b; });