我试图回答这个问题:为什么我们调用 swap 而不是在 reverse 函数的实现中交换*first
and的值?*last
这是反向功能:
template <class BiDirectionalIterator>
void reverse(BiDirectionalIterator first, BiDirectionalIterator last)
{
while(first < last) {
--last;
if(first != last) {
swap(*first++, *last);
}
}
}
我想在这里澄清我的理解。*first
我尝试直接交换*last
:
template <class Bi>
void incorrect_reverse(Bi first, Bi last)
{
while(first < last) {
--last;
if(first != last) {
//here tmp and first both point to the same thing
Bi tmp = first;
*first = *last;
*last = *tmp;
first++;
}
}
}
我看到这不起作用。然后我试图Bi tmp = *first
获取的值,first
但得到一个编译器错误。除了调用swap
我可以做到这一点的函数之外,还有其他方法吗?我正在寻找在函数本身中执行此操作的方法。