为什么 std::swap 不适用于模板项

Why doesnt std::swap work on template items?

本文关键字:适用于 不适用 std swap 为什么      更新时间:2023-10-16

这是我正在试验的一个简单的气泡排序:

template<class T>
void bubbleSort(T *begin, T *end) {
    for (auto index = begin + 1; index != end; ++index) {
        for (auto bubble = begin; bubble != end - 1; ++bubble) {
            if (*bubble > *(bubble + 1)) {
                const T temp = *bubble;
                *bubble = *(bubble + 1);
                *(bubble + 1) = temp;
            }
        }
    }
}

这个版本似乎有效(在其所有的泡沫排序荣耀中)。顺便说一句,这是我正在测试的类,如果它有帮助的话:

class Numbers {
    int max;
    int *numbers;
public:
    Numbers(initializer_list<int> initialList) : max { initialList.size() }, numbers { new int[max] }
    {
        int index = 0;
        for (auto it = initialList.begin(); it != initialList.end(); ++it, ++index) {
            numbers[index] = *it;
        }
    }
    int operator *(int index) { return numbers[index]; }
    int *begin() { return &numbers[0]; }
    int *end() { return &numbers[max]; }
};

我试图做的是使用std::swap在我的内部循环中编写手动交换,如下所示:

for (auto bubble = begin; bubble != end - 1; ++bubble) {
    if (*bubble > *(bubble + 1)) swap (bubble, bubble + 1);
}

但是出于某种原因,编译器告诉我:

error C2665: 'std::swap' : none of the 3 overloads could convert all the argument types

为什么?

swap通过

引用获取其参数。在代码的第一个版本中,您(正确)编写:

const T temp = *bubble;
*bubble = *(bubble + 1);
*(bubble + 1) = temp;

现在考虑如何交换,例如,两个整数:

const int temp = a;
a = b;
b = temp;
// or more simply
swap(a, b);

因此,您的swap应该反映您在第一个正确版本中所做的取消引用:

swap(*bubble, *(bubble + 1));
//   ^ here   ^ and here

>std::swap将引用作为参数。

你给它指点。

你应该做:

swap ( *bubble, *(bubble + 1) );
//     ^        ^

我们取消引用此处的指针以使其正常工作。

您需要取消引用:

swap (*bubble, *(bubble + 1));
相关文章: