std::unique_ptr 支持数组,例如:
std::unique_ptr<int[]> p(new int[10]);
Run Code Online (Sandbox Code Playgroud)
但它需要吗?可能使用std::vector或更方便std::array.
你觉得这个结构有用吗?
这里的用法与将read()直接用于C++ std:vector相同,但具有重新分配的数量.
输入文件的大小未知,因此当文件大小超过缓冲区大小时,通过加倍大小来重新分配缓冲区.这是我的代码:
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
const size_t initSize = 1;
std::vector<char> buf(initSize); // sizes buf to initSize, so &buf[0] below is valid
std::ifstream ifile("D:\\Pictures\\input.jpg", std::ios_base::in|std::ios_base::binary);
if (ifile)
{
size_t bufLen = 0;
for (buf.reserve(1024); !ifile.eof(); buf.reserve(buf.capacity() << 1))
{
std::cout << buf.capacity() << std::endl;
ifile.read(&buf[0] + bufLen, buf.capacity() - bufLen);
bufLen += ifile.gcount();
}
std::ofstream ofile("rebuild.jpg", std::ios_base::out|std::ios_base::binary);
if (ofile)
{
ofile.write(&buf[0], bufLen);
}
}
}
Run Code Online (Sandbox Code Playgroud)
程序按预期打印矢量容量,并将输出文件写入与输入BUT相同的大小,只有与偏移前输入相同的字节initSize,之后全部为零...
使用&buf[bufLen]in …
我有一个 std::vector 值,我知道其最大大小,但实际大小在使用过程中会有所不同:
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
}
void addToBuffer(const Value& v) {
myVector.push_back(v);
if (myVector.size() == maxSize) {
// process data...
myVector.clear();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在 setupBuffer 中,我需要获取指向 myVector 数据开头的指针。我正在使用第三方库,我必须预先缓存该指针,以便在“处理数据...”部分期间进行的调用中使用。
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
cachePtr(&(myVector[0])); // doesn't work, obviously
}
Run Code Online (Sandbox Code Playgroud)
我不想预先 resize() 向量,因为我想使用 vector.size() 来表示添加到向量中的元素数量。
那么,有什么方法可以在分配(reserve())之后但在它有任何元素之前获取指向向量缓冲区的指针吗?我想象缓冲区存在(并且只要我限制 push_back'd 值的数量就不会移动)......也许这不能保证?