1

我试图找到满足:i的向量元素的索引,其中是给定的任意值。我正在尝试使用该函数,但似乎从迭代器而不是迭代器传递值,因此我无法找到执行比较的方法。有没有办法与一元谓词进行比较,如下所示: vv[i] <= x < v[i + 1]xfind_iffind_ifx < v[i + 1]

#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));
4

1 回答 1

4

使用std::adjacent_find,您可以简单地执行以下操作:

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

演示

于 2018-01-29T08:34:37.987 回答