C++ 如何获取指向原始数据的 std::vector 指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6485496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get std::vector pointer to the raw data?
提问by Rookie
I'm trying to use std::vector
as a char
array.
我正在尝试std::vector
用作char
数组。
My function takes in a void pointer:
我的函数接受一个空指针:
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.)?
问题是,我如何将字符向量传递给我的函数,以便我可以访问向量原始数据(无论它是哪种格式 - 浮点数等)?
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
。
回答by James McNellis
&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).
&something
给你std::vector
对象的地址,而不是它保存的数据的地址。 &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.begin()
(the address of the element pointed to by the iterator returned bybegin()
).
&something[0]
或&something.front()
(索引 0 处元素的地址),或&*something.begin()
(由 返回的迭代器指向的元素的地址begin()
)。
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.
在 C++11 中,一个新的成员函数被添加到std::vector
: data()
。这个成员函数返回容器中初始元素的地址,就像&something.front()
. 这个成员函数的优点是即使容器为空也可以调用它。
回答by Chris Dodd
something.data()
will return a pointer to the data space of the vector.
something.data()
将返回一个指向向量数据空间的指针。
回答by Steven Don
Take a pointer to the first element instead:
取一个指向第一个元素的指针:
process_data (&something [0]);