在 std::upper_bound 的自定义比较器函数中获取当前元素的索引

Getting index of the current element in custom comparator function for `std::upper_bound`

我正在尝试使用 std::upper_bound 查找 std::vector<double> xpositions 内元素的上限。 xpositions中每个元素的索引需要用来索引一个多维数组。我试过了

upper_bound(xpositions.cbegin(), xpositions.cend(), value,
            [](const double& element, const double& value){
                // get index of current element
                const auto index = std::distance(xpositions.cbegin(), &element);
                // look up multidimensional array
                bigarray[index];
            }));

但这不会编译,因为 &element 无法转换为迭代器。有没有办法在不做潜在昂贵的 std::find 的情况下获取 element 的索引?

vector 中的元素存储在连续区域中,简单的指针运算即可完成这项工作:

const auto index = &element - &xpositions[0];

您还需要在 lambda 中通过引用捕获 xpositions

如果你想使用 distance,你必须将 vector 的非常量迭代器传递给 upper_bound,并且 predicate 应该采用对 double:

的非常量引用
upper_bound(xpositions.begin(), xpositions.end(), value,
            [&](const double& value, double& element){
                // get index of current element
                auto index = std::distance(&xpositions[0],&element);