1

I am trying to find the index, i, of an element of a vector, v, that satisfies: v[i] <= x < v[i + 1], where x is a given arbitrary value. I am trying to use the find_if function, but it appears that find_if passes the value from the iterator and not the iterator, because of this I cannot figure out a way to perform the x < v[i + 1] comparison. Is there a way to do this comparison with a unary predicate set up the way that I have it below:

#include <vector>
#include <iostream>
#include <algorithm>

//Create predicate for find_if
template<typename T>
struct eq {
    eq(const T _x) : x(x) { };

    //Does not work
    bool operator()(typedef std::vector<T>::iterator it) const {  //
        return *it <= x && x < *(++it);
    }
private:
    T x;
};

//Make vector
std::vector<double> vDouble;
vDouble.push_back(1.5);
vDouble.push_back(3.1);
vDouble.push_back(12.88);
vDouble.push_back(32.4);

double elemVal = *std::find_if(vNumeric.begin(), vNumeric.end(), eq<double>(13.0));
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
EliSquared
  • 1,409
  • 5
  • 20
  • 44
  • 4
    Use [the right tool for the right job](http://en.cppreference.com/w/cpp/algorithm/adjacent_find). – Sam Varshavchik Jan 29 '18 at 05:02
  • And, @1201ProgramAlarm, `std::adjacent_find` is not just for finding "consecutive identical elements", but also for consecutive elements that meet a binary predicate's condition, which may certainly be "the elements are identical", but may also be "the two elements meet some condition that are defined by the arbitrary binary predicate", of which the posed question perfectly satisfies. – Sam Varshavchik Jan 29 '18 at 05:10
  • 1
    @1201ProgramAlarm: That assumes that range is sorted. – Jarod42 Jan 29 '18 at 08:36
  • In your snippet, the vector is sorted. Is this always the case or are you interested in a more general solution? – Bob__ Jan 29 '18 at 09:42

1 Answers1

4

With std::adjacent_find, you may simply do:

const auto x = 13.0;
auto it = std::adjacent_find(v.begin(), v.end(),
                             [x](double lhs, double rhs){ return lhs <= x && x < rhs; });

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302