繁体   English   中英

为什么std :: swap无法在模板项目上使用?

[英]Why doesnt std::swap work on template items?

这是我正在尝试的简单气泡排序:

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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM