从 std:vector 获取数组 [英] Getting array from std:vector
问题描述
从向量中获取字符数组的最简单方法是什么?
What is the easiest way of getting a char array from a vector?
我正在做的方法是使用向量开始和结束迭代器初始化一个字符串,然后从这个字符串中获取 .c_str().还有其他有效的方法吗?
The way I am doing is getting a string initialized using vector begin and end iterators, and then getting .c_str() from this string. Are there other efficient methods?
推荐答案
这在 Scott Meyers 的 Effective STL 中讨论过,你可以做到 &vec[0]
获取 std::vector
的第一个元素的地址,并且由于标准将向量限制为具有连续内存,因此您可以执行此类操作.
This was discussed in Scott Meyers' Effective STL, that you can do &vec[0]
to get the address of the first element of an std::vector
, and since the standard constrains vectors to having contiguous memory, you can do stuff like this.
// some function
void doSomething(char *cptr, int n)
{
}
// in your code
std::vector<char> chars;
if (!chars.empty())
{
doSomething(&chars[0], chars.size());
}
来自评论(感谢卡萨布兰卡)
edit: From the comments (thanks casablanca)
- 注意保存指向这些数据的指针,因为如果向量被修改,指针可能会失效.
这篇关于从 std:vector 获取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!