C++ 如何正确转换向量<;int>;返回到空*并返回到向量<;int>;?

C++ 如何正确转换向量<;int>;返回到空*并返回到向量<;int>;?,c++,pthreads,C++,Pthreads,说明 我需要将一个向量转换为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() {

说明

我需要将一个向量转换为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));
    ...
}
void*比较(void*x){
向量*v=(向量*)x;
向量v1=v[0];
向量v2=v[1];
...
}
int main(){
...
向量x={1,2,3,4};
pthread_create(&threads[i],NULL,compare,static_cast(&x));
...
}
问题

我不明白为什么v包含两个独立的向量。此外,有效值在v1和v2之间旋转;有时一个是垃圾,另一个是有效值。这是我的强制转换/转换的问题还是线程同步的更大问题

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);
}
在本例中,
v1
是指向向量的指针,而不是向量本身。它是指针的基址。当取
v1[0]
时,则取实际向量。您已将vector(而非vector)的地址传递给pthread
(&x)
,这就是为什么需要将其键入vector指针,然后键入vector。

错误的问题。使用
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 f(std::vector&arg);
int main(){
向量参数;
std::thread thr(f,std::ref(参数));
thr.join();
返回0;
}

请尝试
int v1=(*v)[0]
因为
v
是指向向量的指针,而不是向量。请使用std::copy,如果是c++11,请使用static\u cast,因为c语言没有或任何其他模板。因此,请删除
c
tag请提供一个。t您的代码有一些问题,但我不知道您希望代码做什么。
1 2 3
void f(std::vector<int>& arg);

int main() {
    std::vector<int> argument;
    std::thread thr(f, std::ref(argument));
    thr.join();
    return 0;
}