有效地将数据加载到 std::vector<char>

Load data into std::vector<char> efficiently

我的理解是您可以使用指针访问 std::vector 中的数据。例如:

char *ptr;
std::vector<char> v1 {'A', 'B', 'C'};
ptr = &v1[0]
if (*(ptr+1) == 'B')
    std::cout << "Addressing via pointer works\n";

直接加载一个std::vector怎么样?例如:

std::vector<char> v2;
v2.reserve(3); // allocate memory in the vector 
ptr = &v2[0]
*ptr = 'A';
*(ptr+1) = 'B';
*(ptr+2) = 'C';
if (v2[1] == 'B')
    std::cout << "Data is in vector buffer!\n";

但是

if (!v2.size())
    std::cout << "But the vector doesn't know about it!\n";

我的问题:有没有办法告诉v2 vector它的内部内存缓冲区加载了数据?当您想使用 std::vector 来保存来自文件流的数据时,这会很有用。

期待您的评论。

Is there any way to tell the v2 vector that its internal memory buffer is loaded with data?

没有

第二个示例的行为未定义。

This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.

您可以像这样将文件读入矢量:

std::vector<char> v3(count);
ifs.read(v3.data(), count);

或者像这样:

using It = std::istreambuf_iterator<char>;
std::vector<char> v4(It{ifs}, It{});