如何获得由vector :: reserve()分配的缓冲区的地址? [英] How can I get the address of the buffer allocated by vector::reserve()?
问题描述
我有一个std :: vector的值,我知道最大大小,但实际大小将在使用期间变化:
I have a std::vector of values for which I know the maximum size, but the actual size will vary during usage:
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();
}
}
但是,在setupBuffer中,到myVector的数据的开始。我使用的第三方库,我必须缓存这个指针前面用于在过程数据...部分中进行的调用。
However, in setupBuffer, I need to obtain a pointer to the start of myVector's data. I'm using a third party library where I must cache this pointer up front for use in a call made during the "process data..." section.
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
cachePtr(&(myVector[0])); // doesn't work, obviously
}
我不想调整大小)向量前面,因为我想使用vector.size()来表示添加到向量中的元素数量。
I don't want to resize() the vector up front, as I want to use vector.size() to mean the number of elements added to the vector.
所以,有没有办法获得指向分配后的向量缓冲区的指针(reserve()),但在它有任何元素之前?我想象缓冲区存在(只要我限制push_back'd值的数量就不会移动)....也许这不能保证?
So, is there any way to obtain the pointer to the vector's buffer after allocation (reserve()) but before it has any elements? I would imagine the buffer exists (and won't move as long as I restrict the number of push_back'd values)....maybe this isn't guaranteed?
推荐答案
向量缓冲区在调用保留后不会移动,除非超过保留容量。你的问题是获取指向第一个元素的指针。明显的答案是将一个单一的假条目推入向量,获取指向它的指针,然后删除它。
The vector buffer will not be moved after a call to reserve unless you exceed the reserved capacity. Your problem is getting the pointer to the first element. The obvious answer is to push a single fake entry into the vector, get the pointer to it, and then remove it.
更好的方法是如果库接受函数而不是一个指针,当它需要访问缓冲区时,它会调用 - 你可以使函子推迟获取地址,直到缓冲区有一些真正的内容。但是,我意识到你没有改写图书馆的奢侈。
A nicer approach would be if the library accepted a functor rather than a pointer, which it would call when it needed to access the buffer - you could make the functor put off getting the address until the buffer had some real contents. However, I realise you don't have the luxury of rewriting the library.
这篇关于如何获得由vector :: reserve()分配的缓冲区的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!