将向量作为void指针传递给函数 [英] Passing a vector to a function as void pointer

查看:202
本文介绍了将向量作为void指针传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个回调函数,它接受一个 void * 作为参数传递参数,我想传递一个向量到函数。该函数将被多次调用,所以在回调过程完成后,我想能够遍历所有的元素 push_back()'ed通过回调。

  static void cb(void * data)
{
vector< int& * p = static_cast< vector< int> *(data); // Attempting to convert * void to vector< int>
p-> push_back(1);
}

int main()
{
vector< int> a(10); // Max of 10 push_back()s? vector< int>一个;给出内存错误。
cb((void *)& a.at(0));
cout<< a.at(0); //给出6位或更高的随机数字
}

问题是在回调之后调用 a.at(0)时不会正确地具有值1,只是一些随机数。


<假设您不能更改 cb()的签名,请尝试:

  cb(static_cast< void *>(& a)); 


I have a callback function that takes a void * as a parameter to pass arguments to and I'd like to pass a vector to the function. The function will be called multiple times so after the callback process is complete, I'd like to be able to iterate over all the elements that have been push_back()'ed through the callback.

static void cb(void *data)
{
    vector<int> *p = static_cast<vector<int>*>(data); //Attempting to convert *void to vector<int>
    p->push_back(1);
}

int main()
{
    vector<int> a(10); //Max of 10 push_back()s? vector<int> a; gives memory error.
    cb((void*)&a.at(0));
    cout << a.at(0); //Gives a random number of 6 digits or higher
}

The issue is that it does not properly have a value of "1" when a.at(0) is called after the callback, just some random number.

解决方案

Assuming that you cannot change the signature of cb(), try this:

cb(static_cast<void*>(&a));

这篇关于将向量作为void指针传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆