I am having difficulties figuring out how to pass a vector from a thread to the thread function. Its an int vector and this is how I call the thread function for it:
unsigned __stdcall iterative_mergesort(void *v2) {
int increment;
int left;
int left_end;
int right;
int right_end;
int current;
int i;
Vector tmp(v2.size());
int size = v2.size();
increment = 1;
.
.
.
I'm not at a machimne with a compiler on to test this, but I don't think it's the passing to the function that is the problem, it's just how you're casting it in the sorting function, there's a capital V in your (and my copy+paste) vector tmp=that shouldn't be there.
Try simply setting size to the value obtaind from the cast void pointer without using a tmp, I think this would work? int size = ((vector<int>*)v2)->size();
// implementing the mergesort iteratively (bottom up mergesort)
unsigned __stdcall iterative_mergesort(void* v2) {
int increment;
int left;
int left_end;
int right;
int right_end;
int current;
int i;
int size = ((vector<int>*)v2)->size();
// int size = v2.size();
vector<int> tmp(size);
increment = 1;
while (increment < size) {
// I don't need to go over 1 for increment...so I can stop the last pass..
if(increment == 2){
return;}
left = 0;
right = increment;
left_end = right - 1;
right_end = (left_end + increment < size) ? left_end + increment : size - 1;
current = 0;
while (current < size) {
while (left <= left_end && right <= right_end) {
if (v2[right] < v2[left])
tmp[current] = v2[right++];
else
tmp[current] = v2[left++];
current++;
}
while (right <= right_end)
tmp[current++] = v2[right++];
while (left <= left_end)
tmp[current++] = v2[left++];
left = right;
right += increment;
left_end = (right - 1 < size) ? right - 1: size - 1;
right_end = (left_end + increment < size) ? left_end + increment : size - 1;
}
increment *= 2;
for (i = 0; i < size; i++)
v2[i] = tmp[i];
another_function(v2);
}
tmp.empty();
}
you are right Moooce. The problem is not with the parameter passing because the casting works. Does it make a difference if I cast it as ((vector<int>*)v2) instead of ((Vector*)v2)?
Do I need to cast all my v2 in the iterative_mergesort() as well?
I'm afraid I can't compile all that code in my head so you'll have to bare with me if I get something wrong here ;-)
Also I'm no STL guru so maybe somebody else could point you in a more efficient direction, but as far as I know, like you say, you'll need to cast each v2.
The other way may be to wrap your vector in a struct and pass that as you would a normal inbuilt type without having to cast each time, if that fits your needs better?
e.g.
1 2 3 4 5
struct mydata
{
vector<int> Vector1;
int somethingelse;
};
and in your sort function:
1 2
mydata *tmp = (mydata*)v2;
int size=tmp->Vector1.size(); // << here onwards you can use the vector members accessed from tmp.