调整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);
向量,可以假设元素被连续地存储在存储器中,允许范围
[& 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())
.