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