我有以下代码,我编写并完美运行。我只是很难理解它为什么起作用。更具体地说,为什么我们必须首先对数组进行排序才能使用 std::next_permutation,它不能从任何配置开始吗?
最困扰我的部分是我不明白为什么我们必须写 sort(sides,ides+3) 和 next_permutation(sides,ides+3) 为什么是“+3”!因为我在数组中有三个元素?如果我使用任意数量的元素怎么办?
bool valid(int sides[], ofstream &outfile)
{
int i = 0;
for(; i < 3; i++) {
if(sides[i] <= 0) {
outfile << "This is not a valid triangle because it\n "
<< "contains negative sides or contains a\n"
<< "side length of 0\n\n";
return false;
}
}
do{
std::sort(sides,sides+3);
if(sides[0] + sides[1] > sides[2])
;
else{
outfile << "This is not a valid triangle because "
<< sides[0] << " + " << sides[1]
<< " is not greater than " << sides[2];
return false;
}
}while(std::next_permutation(sides,sides+3));
return true;
}