我想寫一個小程序來學習C++ 11多線程程序。所以我決定寫一個mergeSort來測試它。C++ 11多線程合併排序錯誤「沒有構造函數的實例std :: thread'匹配參數列表」
這裏是我的代碼:
class SortMethods
{
protected:
int N;
int *aux;
public:
void mergeSort(int a[])
{
aux = new int[N];
mergeSort(a, 0, N - 1);
}
void merge(int a[], int low, int high)
{
int mid = (low + high)/2;
//optimization 3 for nearly-sorted array
//we can add a condition to improve performance when the array has already sorted or nearly-sorted.
if (a[mid] <= a[mid + 1])
{
return;
}
int i = low;
int j = mid + 1;
for (int k = low; k <= high; k++)
{
aux[k] = a[k];
}
for (int k = low; k <= high; k++)
{
if (i > mid)
a[k] = aux[j++];
else if (j > high)
a[k] = aux[i++];
else if (lessThan(aux[j], aux[i]))
a[k] = aux[j++];
else
a[k] = aux[i++];
}
}
void mergeSort(int a[], int low, int high)
{
if (high <= low)
{
return;
}
int mid = low + (high - low)/2;
//single_thread
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
/*merge(a, low, high);*/
//multi_thread
/*thread left(mergeSort, a, low, mid);
thread right(mergeSort, a, mid + 1, high);
left.join();
right.join();*/
merge(a, low, high);
}
}
int main()
{
int *a = new int(100);
for(int i=0; i<100; i++)
{
a[i] = rand() % 1000;
}
SortMethods sort(100);
sort.mergeSort(a);
}
但是,當我在編譯的VS2015的代碼,它會拋出一個沒有構造「的std ::線程」的實例參數列表相匹配的錯誤。
你能幫我找到我的代碼問題嗎?
=============================================
因爲你們的幫助,我發現,因爲我重載mergeSort方法。我重命名方法mergeSort_multi_thread
thread left(&SortMethods::mergeSort_multi_thread, a, low, mid);
我得到了錯誤 沒有專門的函數模板「未知類型的std ::調用(_Callable & &,_types & & ......)
1> g:\dataalog\datastructuresandalgo\basic_data_structures\sorting.h(240): note: see reference to function template instantiation 'std::thread::thread<void(__thiscall SortMethods::*)(int [],int,int),int&[],int&,int&,void>(_Fn &&,int &[],int &,int &)' being compiled
1> with
1> [
1> _Fn=void (__thiscall SortMethods::*)(int [],int,int)
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
[enter image description here][1]
Thx
您正在使用方法,而不是函數。檢查此答案http://stackoverflow.com/questions/10673585/start-thread-with-member-function瞭解如何傳遞成員函數及其各自的對象 – Nadir
不要評論導致錯誤的代碼,因爲否則人們無法重現錯誤!發佈不起作用的代碼!但是,這已經被答覆了一百萬次。 –