Resizing a C++ std::vectorlt;chargt; without initializing data(调整 C++ std::vectorchar 的大小无需初始化数据)
问题描述
对于向量,可以假设元素连续存储在内存中,允许范围 [&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> 的大小无需初始化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调整 C++ std::vector<char> 的大小无需初始化数据
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01