gpt4 book ai didi

c++ - C++ 中二元谓词的求值

转载 作者:行者123 更新时间:2023-11-30 03:36:07 25 4
gpt4 key购买 nike

二元谓词是如何求值的?

比如我想按降序排序,那么应该这样写:

bool isGreater(int x, int y) 
{
return x > y;
}

bool isGreater(int x, int y) 
{
return y > x;
}

两者到底有什么区别?我知道这两个参数会相互比较,但返回结果应该是什么 - truefalse?这有什么关系呢?所以,我的问题基本上是,如果我不知道第一个参数的传递顺序,我如何确定第一个参数是否应该在第二个参数之前?

sort() 函数将以这种方式调用(height 是要排序的数组):

sort(height, height+N, isGreater);

注意:我确实引用了像 this one 这样的链接和 this one ,但他们没有明确关注这个问题。

有人可以澄清我的疑问吗?谢谢!

最佳答案

这是一个非常简单的伪代码升序排序算法:

for i ← 1 to length(A)-1
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
end for

与谓词“MyCompare(x, y) { return x <= y; }”相同的事情看起来像这样:

for i ← 1 to length(A)-1
j ← i
while j > 0 and MyCompare(A[j-1], A[j]) == false
swap A[j] and A[j-1]
j ← j - 1
end while
end for

现在,排序算法只需更改谓词即可按任意顺序排序。由于此谓词是 std::sort 的参数,这意味着 std::sort 可以按任何顺序排序。

关于c++ - C++ 中二元谓词的求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com