为什么 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));
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 使用程序集嵌入数据时"Undefined reference"错误,使用适用于窗口的 mingw-w64 编译(COFF 而不是 ELF)
- 为什么 std::vector 适用于类定义中的不完整类型?
- 为什么哈希<常量字符*>适用于字符串而不是字符串变量?
- Lambda适用于最新的Visual Studio,但在其他地方不起作用
- 我该如何文档文档以使文档适用于类成员而不是匿名类型
- 计算 c# 中二进制文件符号的频率不起作用,但适用于等效的 c++ 代码
- 为什么 fstream.open(文件名) 适用于文字而不是生成的字符串?
- 模板重载和 SFINAE 仅适用于函数而不是类
- 为什么链接器不抱怨多个函数定义(仅适用于模板化函数)
- 我可以使用' == '来比较两个向量吗?我试过了,似乎工作正常。但我不知道它是否适用于更复杂的情况
- 延长临时的生命周期,适用于块范围的聚合,但不是通过"新";为什么?