简体   繁体   English

如何获取原始数据的std :: vector指针?

[英]How to get std::vector pointer to the raw data?

I'm trying to use std::vector as a char array. 我正在尝试使用std::vector作为char数组。

My function takes in a void pointer: 我的函数接受一个void指针:

void process_data(const void *data);

Before I simply just used this code: 在我刚刚使用此代码之前:

char something[] = "my data here";
process_data(something);

Which worked as expected. 哪个按预期工作。

But now I need the dynamicity of std::vector , so I tried this code instead: 但是现在我需要std::vector的动态性,所以我尝试了这个代码:

vector<char> something;
*cut*
process_data(something);

The question is, how do I pass the char vector to my function so I can access the vector raw data (no matter which format it is – floats, etc.)? 问题是,如何将char矢量传递给我的函数,以便我可以访问矢量原始数据(无论是哪种格式 - 浮点数等)?

I tried this: 我试过这个:

process_data(&something);

And this: 还有这个:

process_data(&something.begin());

But it returned a pointer to gibberish data, and the latter gave warning: warning C4238: nonstandard extension used : class rvalue used as lvalue . 但它返回了指向乱码数据的指针,后者发出警告: warning C4238: nonstandard extension used : class rvalue used as lvalue

&something gives you the address of the std::vector object, not the address of the data it holds. &something为您提供std::vector对象的地址,而不是它所拥有的数据的地址。 &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken). &something.begin()为您提供了begin()返回的迭代器的地址(正如编译器警告的那样,这在技术上是不允许的,因为something.begin()是一个右值表达式,因此无法获取其地址)。

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via 假设容器中至少有一个元素,您需要获取容器的初始元素的地址,您可以通过该地址获取

  • &something[0] or &something.front() (the address of the element at index 0), or &something[0]&something.front() (索引0处元素的地址),或

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin() ). &*something.begin() (由begin()返回的迭代器指向的元素的地址)。

In C++11, a new member function was added to std::vector : data() . 在C ++ 11中,一个新的成员函数被添加到std::vectordata() This member function returns the address of the initial element in the container, just like &something.front() . 此成员函数返回容器中初始元素的地址,就像&something.front() The advantage of this member function is that it is okay to call it even if the container is empty. 这个成员函数的优点是即使容器为空也可以调用它。

something.data()将返回指向向量数据空间的指针。

改为使用指向第一个元素的指针:

process_data (&something [0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM