下面是我正在试验的一种简单的气泡类型:
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为什么会这样呢?
发布于 2013-09-06 19:15:19
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发布于 2013-09-06 19:17:24
std::swap将引用作为参数。
你在给它指点。
你应该这样做:
swap ( *bubble, *(bubble + 1) );
// ^ ^我们取消这里的指针,以使它工作。
发布于 2013-09-06 19:14:55
你需要取消你的尊重:
swap (*bubble, *(bubble + 1));https://stackoverflow.com/questions/18664952
复制相似问题