C++ 如何获得指向 std::vector 中第一个元素的指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7377773/
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 can I get a pointer to the first element in an std::vector?
提问by Luc Danton
I want to write data from an std::vector<char>
to a socket, using the write
function, which has this prototype:
我想std::vector<char>
使用write
具有以下原型的函数将数据从 an 写入套接字:
ssize_t write(int, const void *, size_t);
The second argument to this function must be a pointer to the first element in the std::vector<char>
. How can I get a pointer to this element?
此函数的第二个参数必须是指向std::vector<char>
. 如何获得指向该元素的指针?
I tried std::vector::front
but this returns a reference, while I need a pointer.
我试过了,std::vector::front
但这会返回一个引用,而我需要一个指针。
采纳答案by Oliver Charlesworth
&mv_vec[0]
or
或者
&my_vec.front()
回答by Luc Danton
C++11 has vec.data()
which has the benefit that the call is valid even if the vector is empty.
C++11vec.data()
的好处是即使向量为空,调用也是有效的。
回答by Armen Tsirunyan
my_vec.empty() ? 0 : &my_vec.front()
If you would like an std::out_of_range
to be thrown if vector is empty, you could use
如果您希望std::out_of_range
在 vector 为空时抛出an ,您可以使用
&my_vec.at(0)
回答by B?ови?
&*my_vec.begin()
or
或者
&mv_vec[0]
回答by Christian Rau
By taking the address of the first element, with &vec[0]
, as the standard (since C++03, I think) demands continous storage of std::vector
elements.
通过获取第一个元素的地址&vec[0]
,作为标准(我认为是 C++03 起)需要std::vector
元素的连续存储。