C++的reverse函数在algorithm头文件中,用来翻转 [a, b) 之间的内容。
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
while ((first!=last)&&(first!=--last))
{
std::iter_swap (first,last);
++first;
}
}
例如:
int a[] = {1, 2, 3, 4, 5, 6, 7};
reverse(&a[0], &a[2]);
for (int i = 0; i < 7; i++) {
cout << a[i] << endl;
}
输出:
2
1
3
4
5
6
7