gpt4 book ai didi

c++ - next_permutation 与自定义比较器函数 c++

转载 作者:行者123 更新时间:2023-11-30 03:51:59 26 4
gpt4 key购买 nike

我正在为 next_permutation 函数使用自定义比较器函数,但我不明白为什么会出现错误:

Expression: invalid operator<

我希望我的函数至少在函数体中使用这些限制,但不断出现错误:

bool mycomp(int i, int j)
{
return (((i < 0) && (j > 0)) || ((i > 0) && (j < 0)));
};

但是当我这样做时,它工作正常:

bool mycomp(int i, int j)
{
return (((i < 0) && (j > 0)));
};

我还想添加另一个限制,但不知道如何添加。下面是带有 next_permutation 函数的相关代码:

int counter, size, *guests;
for (int i = 2; i <= 9; i++)
{
size = i * 2;
counter = 1;
guests = new int[size];
for (int j = 0; j < size; j += 2)
{
guests[j] = counter;
guests[j + 1] = 0 - counter;
++counter;
}
sort(guests, guests + size);
counter = 0;
while (next_permutation(guests, guests + size, mycomp))
{
++counter;
}
}

我也知道有严格的弱排序要求。阅读后我理解了它的要点,但不确定它究竟如何适用于这种情况。提前谢谢你。

最佳答案

您的编译器试图告诉您(通过运行时断言)您的比较器无效。它是无效的,因为它至少有两个原因不遵守严格的弱排序契约(Contract):

1) 它不是反对称(即 f(x, y) 意味着 !f(y, x)):

std::cout << mycomp(2, -3) << '\n';
std::cout << mycomp(-3, 2) << '\n';

输出:

true
true

2) 它不是可传递的(即 f(x, y) 和 f(y, z) 暗示 f(x, z) ):

std::cout << mycomp(2, -3) << '\n';
std::cout << mycomp(-3, 2) << '\n';
std::cout << mycomp(2, 2) << '\n';

输出:

true
true
false
false

Demo

您可能需要重新考虑您的问题,以及在进行排列时您真正希望如何对元素进行排序。

关于c++ - next_permutation 与自定义比较器函数 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971031/

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