获取阵列从STD:向量 [英] 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?
推荐答案
这是在斯科特迈尔斯讨论'的的Effective STL 的,你可以做&放大器; VEC [0]
来获得的std ::矢量
的第一个元素的地址,因为标准约束向量有连续的内存,你可以做的东西是这样的。
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:向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!