How to get std::vector pointer to the raw data?
I'm trying to use std::vector
as a char
array.
My function takes in a void pointer:
void process_data(const void *data);
Before I simply just used this code:
char something开发者_StackOverflow[] = "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:
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.)?
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
.
&something
gives you the address of the std::vector
object, not the address of the data it holds. &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).
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.begin()
(the address of the element pointed to by the iterator returned bybegin()
).
In C++11, a new member function was added to std::vector
: data()
. This member function returns the address of the initial element in the container, just like &something.front()
. The advantage of this member function is that it is okay to call it even if the container is empty.
something.data()
will return a pointer to the data space of the vector.
Take a pointer to the first element instead:
process_data (&something [0]);
精彩评论