【问题标题】:Getting index of the current element in custom comparator function for `std::upper_bound`在 `std::upper_bound` 的自定义比较器函数中获取当前元素的索引
【发布时间】:2021-10-05 16:33:46
【问题描述】:

我正在尝试使用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 无法转换为迭代器。有没有办法获得element 的索引,而无需执行可能昂贵的std::find

【问题讨论】:

  • 您如何知道valueelement 中的哪些引用引用了vector 中的元素?我认为您的比较器定义不明确。
  • 我错误地将它们倒退了。我将编辑帖子。
  • 算法不要求使用特定顺序的参数调用比较器。事实上,Visual C++ 库的调试版本将调用这两个命令来验证您的比较器没有违反严格的弱命令。你的方法注定失败。如果您需要索引进行比较,则必须以其他方式明确提供。您不能从参数中得出它。
  • From cppreference: "Type1 类型必须是 T 类型的对象可以隐式转换为 Type1Type2 类型必须是这样的对象ForwardIt 类型的可以取消引用,然后隐式转换为 Type2。"这不是暗示第一个参数是upper_bound 的第三个参数,而第二个参数是取消引用的值吗?
  • 有趣!看来你说得有道理,我错了。

标签: c++ stl


【解决方案1】:

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

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

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

如果你想使用distance,你必须将vector的非常量迭代器传递给upper_bound,并且谓词应该对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);

【讨论】:

  • 第一个sn-p不就是计算字节地址差吗?我们不需要除以double的大小吗?我也不知道std::distance 接受原始指针。它没有显示为 possible overloads 之一。
  • 如果指针 P 指向数组的第 i 个元素,而指针 Q 指向同一个数组的第 j 个元素,则表达式 PQ 的值为 ij,如果该值符合在 std::ptrdiff_t 中。两个操作数都必须指向同一个数组的元素(或最后一个),否则行为未定义。如果结果不适合 std::ptrdiff_t,则行为未定义。 cppreference 它为您提供两个指针之间的项目数。
猜你喜欢
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
相关资源
最近更新 更多