调整 C++ std::vector<char> 的大小无需初始化数据 [英] Resizing a C++ std::vector&lt;char&gt; without initializing data

查看:135
本文介绍了调整 C++ std::vector<char> 的大小无需初始化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于向量,可以假设元素连续存储在内存中,允许范围 [&vec[0], &vec[vec.capacity()) 用作正常数组.例如,

With vectors, one can assume that elements are stored contiguously in memory, allowing the range [&vec[0], &vec[vec.capacity()) to be used as a normal array. E.g.,

vector<char> buf;
buf.reserve(N);
int M = read(fd, &buf[0], N);

但现在向量不知道它包含 M 字节的数据,由 read() 从外部添加.我知道 vector::resize() 设置大小,但它也清除数据,所以它不能用于更新 read() 后的大小打电话.

But now the vector doesn't know that it contains M bytes of data, added externally by read(). I know that vector::resize() sets the size, but it also clears the data, so it can't be used to update the size after the read() call.

是否有一种简单的方法可以将数据直接读入向量并在之后更新大小?是的,我知道一些明显的解决方法,例如使用小数组作为临时读取缓冲区,并使用 vector::insert() 将其附加到向量的末尾:

Is there a trivial way to read data directly into vectors and update the size after? Yes, I know of the obvious workarounds like using a small array as a temporary read buffer, and using vector::insert() to append that to the end of the vector:

char tmp[N];
int M = read(fd, tmp, N);
buf.insert(buf.end(), tmp, tmp + M)

这行得通(这就是我今天要做的),但让我烦恼的是,如果我可以将数据直接放入其中,则不需要额外的复制操作矢量.

This works (and it's what I'm doing today), but it just bothers me that there is an extra copy operation there that would not be required if I could put the data directly into the vector.

那么,在外部添加数据时,有没有一种简单的方法可以修改矢量大小?

So, is there a simple way to modify the vector size when data has been added externally?

推荐答案

vector<char> buf;
buf.reserve(N);
int M = read(fd, &buf[0], N);

此代码片段调用未定义的行为.你不能写超过 size() 元素,即使你已经预留了空间.

This code fragment invokes undefined behavior. You can't write beyond than size() elements, even if you have reserved the space.

正确的代码如下:

vector<char> buf;
buf.resize(N);
int M = read(fd, &buf[0], N);
buf.resize(M);


PS. 您的陈述对于向量,人们可以假设元素连续存储在内存中,允许范围 [&vec[0], &vec[vec.capacity()) 用作普通数组"是不正确的.允许的范围是[&vec[0], &vec[vec.size()).


PS. Your statement "With vectors, one can assume that elements are stored contiguously in memory, allowing the range [&vec[0], &vec[vec.capacity()) to be used as a normal array" isn't true. The allowable range is [&vec[0], &vec[vec.size()).

这篇关于调整 C++ std::vector<char> 的大小无需初始化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆