无论我在visual studio中构建我的代码,我都会得到以下内容
严重级代码描述项目文件行抑制状态 错误C2672'std :: invoke':找不到匹配的重载函数Quicksort c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread 238
和
严重级代码描述项目文件行抑制状态 错误C2893无法专门化函数模板'unknown-type std :: invoke(_Callable&&,_ Types&& ...)'Quicksort c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread 238
没有线程,代码可以正常使用递归。虽然我想实现2个线程,递归调用quicksort。每个线程占用阵列的一半,一个是左,一个是右。我是否正确地调用了线程?
#include <iostream>
#include <thread>
#include <fstream>
#include <vector>
using namespace std;
vector<int> quickSort(vector<int> &arr, int &start, int &end) {
//Set starting left and right positions for the iteration to come
int pos_left = start;
int pos_right = end;
int tmp;
//Set pivot value
int pivot = arr[(start + end) / 2];
//The algorithm will run as long as the right position and the left
//position don't pass each other. It will stop when they both reach the
//same position
while (pos_left <= pos_right) {
//Increments left position until value at position is greater than
//the pivot
while (arr[pos_left] < pivot)
pos_left++;
//Decrements right position until value at position is smaller than
//the pivot
while (arr[pos_right] > pivot)
pos_right--;
//Swaps value at left position with value at right position then
//increments left position and decrements right position
if (pos_left <= pos_right) {
tmp = arr[pos_left];
arr[pos_left] = arr[pos_right];
arr[pos_right] = tmp;
pos_left++;
pos_right--;
}
}
//Initialize threads. First thread will sort the resulting left partition
//and second thread will sort the resulting right partition of the vector
thread first (quickSort,arr, start, pos_right);
thread second (quickSort, arr, pos_left, end);
//The first thread will run until the left partition is sorted
if (start < pos_right)
first.join();
//The second thread will run until the right partition is sorted
if (pos_left < end)
second.join();
return arr;
}
int main() {
vector<int> myVector;
//Read the file "array.txt" file onto a vector
ifstream file("array.txt");
if (file.is_open()) {
int val;
while (file >> val) {
myVector.push_back(val);
}
myVector.erase(myVector.begin());
}
//Set position of first value in vector
int start = 0;
//Set position of last value in vector
int end = myVector.size() - 1;
//Call the sorting alogrithm which takes starting position and end position of
//last vector value.
vector<int> sorted = quickSort(myVector, start, end);
//Write the sorted vector onto a text file "sorted.txt"
ofstream myfile;
myfile.open("sorted.txt");
for (int i = 0; i < sorted.size(); i++) {
myfile << sorted[i];
myfile << endl;
}
myfile.close();
}