简体   繁体   English

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

[英]How to convert char* to std::vector?

I have a char* variable: 我有一个char *变量:

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

How can I convert it to std::vector? 我怎样才能将它转换为std :: vector? Casting will get me an error. 施法将给我一个错误。

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

詹姆斯麦克纳利斯的回答是更好的,如果你能做到这一点。

Why not use a std::vector to begin with: 为什么不使用std::vector开头:

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

You can't cast between a char* and a vector; 你不能在char *和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. 指针转换导致结果与输入具有完全相同的字节,因此除非您正在执行低级位操作,否则通常是个坏主意。

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: 假设你想构建一个chars向量,你可以创建一个std::vector<char>类型的新向量对象(注意你需要提供向量元素的类型),并通过传递它来从数组中初始化它。开始和结束指向构造函数的指针:

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

Note that the second argument is an "end pointer", very common in C++. 请注意,第二个参数是“结束指针”,在C ++中很常见。 Importantly, it is a pointer to the character after the end of the buffer, not the last character in the buffer. 重要的是,它是缓冲区结束的字符指针,而不是缓冲区中的最后一个字符。 In other words, the start is inclusive but the end is exclusive. 换句话说,开始是包容性的,但结束是排他性的。

Another possibility (since you're dealing with chars) is to use a std::string instead. 另一种可能性(因为你正在处理字符)是使用std::string代替。 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). 这可能是您想要的也可能不是(取决于您是将char *视为字符串还是字节数组)。 You can construct it in the same way: 您可以以相同的方式构建它:

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

or with a different constructor, taking the size as the second argument: 或者使用不同的构造函数,将大小作为第二个参数:

std::string str(buffer, lSize);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM