如何找到排序向量的下界
我对 C++ 还很陌生,并不理解 STL 库的所有概念,所以请耐心等待。 我编写了以下代码片段(粘贴在下面)来查找排序向量中的 lower_bound 。 尽管此代码在发布模式下工作正常,但它在调试模式 (VStudio-8) 下断言。 我相信这是因为 less_equal
不是严格的弱排序。
从以下线程: stl 排序 - 严格弱排序
我确实有点理解弱排序是由STL强加的,但我仍然不太清楚为什么?
在下面的例子中,我需要使用 less_equal
因为我试图在排序向量中找到最接近给定值的元素。
下面的代码片段是否有效?另外,有更好的方法吗?此外,任何对薄弱环节和部分排序的见解/参考都会有所帮助。
int main() {
vector<int> dest;
for(int i = 0;i <6;i++) {
dest.push_back(i);
}
vector<int>::iterator i =
std::lower_bound(dest.begin(),dest.end(),4,less_equal< int >());
return 1;
}
I'm pretty new to C++ and do not understand all the concepts of the STL library, so bear with me.
I wrote the following code snippet (pasted below) to find the lower_bound in a sorted vector.
Although this code works fine in Release mode, it asserts in debug mode (VStudio-8).
I believe this is because less_equal<int>
is not a strictly weak ordering .
From the following thread: stl ordering - strict weak ordering
I do sort of understand that a weak ordering is imposed by the STL, but I'm still not very clear why?
In my case below I need to use less_equal<int>
since I'm trying to find the nearest element to a given value in a sorted vector.
Is the code snippet below even valid? Also, is there a better way to do it? Also any insights/references to what exactly is weak and partial ordering would be helpful.
int main() {
vector<int> dest;
for(int i = 0;i <6;i++) {
dest.push_back(i);
}
vector<int>::iterator i =
std::lower_bound(dest.begin(),dest.end(),4,less_equal< int >());
return 1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
STL 使用严格的弱排序,因为给定一个 SWE(让我们将其表示为
<
),您可以定义所有六个关系运算符:至于您要解决的问题,如果您想要值尽可能接近目标值,你真的不需要在这里使用
less_equal
。相反,使用lower_bound
获取大于您要查找的值的最小元素的迭代器(对整数使用默认的<
比较),然后比较该值到它之前的值(当然,假设这两个值都存在!)lower_bound
中的值是最小与 x 一样大的元素,并且该值之前的元素是最大值 no大于 x,因此两者之一必须是最接近的。至于程序为何断言,很可能是因为
<=
不是严格的弱排序,但我不能确定这一点。更改为使用上述方法应该可以解决问题,除非问题来自其他来源。The STL uses strict weak orderings because given a SWE (let's denote it
<
), you can define all six of the relational operators:As for the problem you're trying to solve, if you want the value as close as possible to the target value, you really don't need to use
less_equal
here. Rather, uselower_bound
to get an iterator to the smallest element bigger than the value you're looking for (using the default<
comparison on integers), then compare that value to the value before it (assuming, of course, that both these values exist!) The value fromlower_bound
is the smallest element as least as large as x and the element before that value is the largest value no greater than x, so one of the two must be the closest.As for why the program was asserting, it's quite possible that it's due to the fact that
<=
is not a strict weak ordering, but I can't be certain about that. Changing to using the above approach should fix it unless the problem is from some other source.