C++ 从 std:vector 获取数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4289612/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:02:56  来源:igfitidea点击:

Getting array from std:vector

c++arraysvector

提问by SkypeMeSM

What is the easiest way of getting a char array from a vector?

从向量中获取字符数组的最简单方法是什么?

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?

我正在做的方法是使用向量开始和结束迭代器初始化一个字符串,然后从这个字符串中获取 .c_str() 。还有其他有效的方法吗?

回答by econoclast

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.

这在 Scott Meyers 的Effective STL 中进行了讨论,您可以这样做&vec[0]来获取 an 的第一个元素的地址std::vector,并且由于标准将向量限制为具有连续内存,因此您可以执行以下操作。

// 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)

编辑:来自评论(感谢卡萨布兰卡)

  • be wary about holding pointers to this data, as the pointer can be invalidated if the vector is modified.
  • 小心保存指向此数据的指针,因为如果修改向量,则指针可能会失效。

回答by ronag

std::vector<char> chars;
char* char_arr = chars.data(); // &chars[0]