C++ 如何将 char* 转换为 std::vector?

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

How to convert char* to std::vector?

c++

提问by Richard Knop

I have a char* variable:

我有一个 char* 变量:

// char* buffer;
// ...
fread (buffer, 1, lSize, pFile);
// ...

How can I convert it to std::vector? Casting will get me an error.

如何将其转换为 std::vector?铸造会让我出错。

采纳答案by James McNellis

Why not use a std::vectorto begin with:

为什么不使用 astd::vector开头:

std::vector<char> buffer(lSize);
std::fread(&buffer[0], 1, buffer.size(), pFile);

回答by ronag

std::vector<char> data(buffer, buffer + size);

James McNellis answer is better if you can do it like that.

如果你能这样做,詹姆斯麦克内利斯的回答会更好。

回答by mgiuca

You can't cast between a char* and a vector; pointer casting causes the result to have the exact same bytes as the input, so it's generally a bad idea unless you're doing low-level bit manipulation.

你不能在 char* 和 vector 之间进行转换;指针转换会导致结果与输入具有完全相同的字节,因此除非您进行低级位操作,否则这通常是一个坏主意。

Assuming you wanted to build a vector of chars, you can create a new vector object of type std::vector<char>(note that you need to supply the type of the vector's elements), and initialise it from the array by passing the begin and end pointers to the constructor:

假设您想构建一个字符向量,您可以创建一个新的向量类型对象std::vector<char>(请注意,您需要提供向量元素的类型),并通过将开始和结束指针传递给构造函数来从数组中初始化它:

std::vector<char> vec(buffer, buffer+lSize);

Note that the second argument is an "end pointer", very common in C++. Importantly, it is a pointer to the character afterthe end of the buffer, not the last character in the buffer. In other words, the start is inclusive but the end is exclusive.

请注意,第二个参数是“结束指针”,在 C++ 中很常见。重要的是,它是指向缓冲区末尾之后的字符的指针,而不是缓冲区中的最后一个字符。换句话说,开始是包容性的,但结束是排斥性的。

Another possibility (since you're dealing with chars) is to use a std::stringinstead. This may or may not be what you want (depending on whether you're thinking about the char* as a string or an array of bytes). You can construct it in the same way:

另一种可能性(因为您正在处理字符)是使用 astd::string代替。这可能是也可能不是您想要的(取决于您是将 char* 视为字符串还是字节数组)。你可以用同样的方式构造它:

std::string str(buffer, buffer+lSize);

or with a different constructor, taking the size as the second argument:

或者使用不同的构造函数,将大小作为第二个参数:

std::string str(buffer, lSize);