独自のテンプレート スワップ関数を作成しようとしていますが、このコードには何か問題があります。
template <class T>
void swap_universal(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
この 2 行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
関数内で新しいスワップ関数が呼び出されます