C++ 线程模板矢量快速排序

史蒂文来吧

线程快速排序方法:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "MD5.h"
#include <thread>
using namespace std;

template<typename T>
void quickSort(vector<T> &arr, int left, int right) {
    int i = left, j = right; //Make local copys to modify
    T tmp; //Termorary variable to use for swaping.
    T pivot = arr[(left + right) / 2]; //Find the centerpoint. if 0.5 truncate.

    while (i <= j) {
        while (arr[i] < pivot) //is i < pivot?
            i++;
        while (arr[j] > pivot) //Is j > pivot?
            j--;
        if (i <= j) {          //Swap
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    };

    thread left_t; //Left thread
    thread right_t; //Right thread
    if (left < j)
        left_t = thread(quickSort<T>, ref(arr), left, j);

    if (i < right)
        right_t = thread(quickSort<T>, ref(arr), i, right);

    if (left < j)
        left_t.join();
    if (left < j)
        right_t.join();
}


int main()
{
    vector<int> table;
    for (int i = 0; i < 100; i++)
    {
        table.push_back(rand() % 100);
    }
    cout << "Before" << endl;
    for each(int val in table)
    {
        cout << val << endl;
    }
    quickSort(table, 0, 99);
    cout << "After" << endl;
    for each(int val in table)
    {
        cout << val << endl;
    }
    char temp = cin.get();
    return 0;
}

上面的程序像疯狂的地狱一样滞后,垃圾邮件“abort()”已被调用。

我认为它与向量有关,并且存在线程问题

我看到了 Daniel Makardich 提出的问题,他使用 Vector int 而我的使用 Vector T

luk32

快速排序没有任何问题,但将模板化函数传递给线程。没有功能quickSort您需要明确给出类型,以实例化函数模板:

#include <thread>
#include <iostream>

template<typename T>
void f(T a) { std::cout << a << '\n'; }

int main () {
    std::thread t;
    int a;
    std::string b("b");
    t = std::thread(f, a); // Won't work
    t = std::thread(f<int>, a);
    t.join();
    t = std::thread(f<decltype(b)>, b); // a bit fancier, more dynamic way
    t.join();
    return 0;
}

我怀疑你的情况应该这样做:

left_t = thread(quickSort<T>, ref(arr), left, j);

和 类似right_t此外,您在尝试使用operator()()而不是构造对象时出错这就是错误不同的原因。

无法验证,因为没有最小的可验证示例 =/

我不知道是否可以让编译器使用自动类型推导f作为参数传递,如果有人知道这可能会使它成为更好的答案。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章