【发布时间】:2015-10-26 09:13:29
【问题描述】:
我正在尝试编写自己的模板交换函数,但这段代码有问题:
template <class T>
void swap_universal(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
在这两行:a = b 和 b = tmp 我收到错误 read only variable is not assignable。我正在使用 Xcode。
UPD:这是完整的代码:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
template <class T>
void swap_universal(T &&a, T &&b) {
T tmp = a;
a = b;
b = tmp;
}
template <typename T>
void quick_Sort(const int &start, const int &end, const vector<T> &mas/*, const vector<T> arr*/) {
int left = start, right = end;
int middle = rand() % (end - start) + start;
while (left < right) {
while (mas[left] < middle)
left++;
while (mas[right] > middle)
right--;
if (left <= right) {
swap_universal(mas[left], mas[right]);
left++;
right--;
}
}
if (start < right)
quick_Sort(start, right, mas);
if (end > left)
quick_Sort(left, end, mas);
}
int main(int argc, const char * argv[]) {
vector<int> t;
for (int i = 100; i >= 0; i--) {
t.push_back(i);
}
quick_Sort(0, t.size() - 1, t);
}
如您所见,quick_Sort 函数内部调用了新的交换函数
【问题讨论】:
-
你用什么调用这个函数?
-
请编辑您的问题以包含Minimal, Complete, and Verifiable Example。还包括实际、完整且未经编辑的错误输出。
-
您正在使用 const 对象作为参数调用函数
-
std::swap有什么问题? -
向量
mas是对常量向量的引用,你不能修改它。在参数声明中删除const关键字。
标签: c++ template-function