为什么我们需要交换反向 STL 实现?加速 C++(问题 8.4)

Why do we need swap in reverse STL implementation? Accelerated C++ (ques 8.4)

我正在尝试回答这个问题: 为什么我们在reverse函数的实现中调用swap而不是交换*first*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 函数更能做到这一点的方法?我正在寻找在函数本身中执行此操作的方法。

您需要将值 *first 存储为临时存储,而不是迭代器 first

auto tmp = *first;
*first = *last;
*last = tmp;
first++;

否则你将覆盖 *first 而不存储它以前的值,所以你实际上只是从 *last 复制到 *first (然后再次冗余地复制它),而不是交换。

执行此操作时出现错误的原因:

Bi tmp = *first

是因为Bi是迭代器的类型,而不是你要交换的值的类型。要获得正确的类型,您可以像我上面那样使用 auto,或者您可以更明确:

typename std::iterator_traits<Bi>::value_type tmp = *first;