如何比较两个相等但一个按升序排列而另一个按降序排列的数组?
int array1[] = {1,2,3,4,5};
int array2[] = {5,4,3,2,1};
if (std::equal(std::begin(array1), std::end(array1), std::begin(array2)))
cout << "Arrays are equal.";
else
cout << "Arrays are not equal.";
现在两个数组相等,但一个是升序,另一个是降序,所以这段代码的输出是“数组不相等”,我们如何输出“数组相等”?
回答
使用reverse_iterator:
std::equal(std::begin(array1), std::end(array1), std::rbegin(array2))
- @MohsanAli It also compiles to very efficient code. Here it is on [Compiler Explorer](https://godbolt.org/z/Eob73s), the inner loop is only 7 assembly instructions.