[英]How to properly convert a vector<int> to a void* and back to a vector<int>?
描述
我需要將向量轉換為void *,以便可以將其作為參數傳遞給通過pthread調用的函數。 在該函數中,我需要將void *轉換回向量,以便訪問其元素。
碼
void* compare(void* x) {
vector<int>* v = (vector<int>*)x;
vector<int> v1 = v[0];
vector<int> v2 = v[1];
...
}
int main() {
...
vector<int> x = {1, 2, 3, 4};
pthread_create(&threads[i], NULL, compare, static_cast<void*>(&x));
...
}
問題
我不明白為什么v包含2個單獨的向量。 此外,有效值在v1和v2之間旋轉; 有時一個是垃圾,另一個是有效值。 這是我的轉換/轉換問題還是線程同步的更大問題?
錯誤的問題。 <g>使用std::thread
,它知道如何處理參數類型:
void f(std::vector<int>& arg);
int main() {
std::vector<int> argument;
std::thread thr(f, std::ref(argument));
thr.join();
return 0;
}
void* compare(void* x) {
vector<int>* v1 = (vector<int>*)(x);
vector<int> v = v1[0]; // it will always be v[0]
cout << v[0] << " " << v[1] << " " << v[2];
}
int main() {
pthread_t thread;
vector<int> x = {1, 2, 3, 4};
pthread_create(&thread, NULL, compare, static_cast<void*>(&x));
pthread_join( thread, NULL);
}
要么
void* compare(void* x) {
vector<int> v = ((vector<int>*)x)[0];
cout << v[0] << " " << v[1] << " " << v[2];
}
輸出:
1 2 3
在此示例中, v1
是指向矢量的指針,而不是矢量本身。 它是指針的基地址。 當采用v1[0]
則采用實際向量。 您已將向量(不是向量)的地址傳遞給pthread (&x)
,這就是為什么您需要先將其類型轉換為向量指針,然后再向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.