I'm currently learning C++ and for my current goal I want to fill values from vector A
into vector X
. vector X
must not be larger than 20. To archive this I have a function that checks if the current vector has space left. If no space is left, it replaces the current vector with a new vector from a template (which already contains some entries, that have to be the same for all the vectors):
int ChunkedBufferBuilder::checkNewBuffer() {
int space_left = chunk_size - super::current.size();
if (space_left == 0) {
bufVec.push_back(super::current);
super::current = tpl;
space_left = chunk_size - super::current.size() ;
}
return space_left;
}
bufVec
is another vector holding all vectors that have reached a size of 20. This function returns always the remaining amount of "free" entries in the current Vector.
To prevent having to insert every single value from the input vector in to the smaller vectors, I'm trying to use the insert
function here:
ChunkedBufferBuilder* ChunkedBufferBuilder::push_back(const std::vector<uint8_t> &vec) {
auto pos = 0;
const auto size = vec.size();
while (pos < size) {
const int space_left = checkNewBuffer();
const int to = (space_left > size - pos) ? size : pos + space_left;
auto fromPtr = vec.at(pos);
auto toPtr = vec.at(to);
int size = super::current.size();
super::current.insert(super::current.end(), fromPtr, toPtr);
size = super::current.size();
pos = to;
}
return this;
}
Note, that the second size = super::current.size()
was placed there by me for helping to debug. In the following images I have set two breakpoints. One on the line where insert
is called and the other one on the pos = to
assignment.
The documentation of std::vector
states that:
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
Thus I expect that the size increases by the amount of elements, that I added. But when I run the debugger:
I get these values at the first breakpoint:
And at the second breakpoint size
only increased by one:
However on the second pass of the while loop, it then tries to insert another twelve values ( size
is still 8 so 20 - 8 == 12
):
And then suddenly the size jumps to 22:
This is currently breaking my program and I'm pretty much clueless why my code behaves in the way it currently does.
In this snippet:
auto fromPtr = vec.at(pos);
auto toPtr = vec.at(to);
super::current.insert(super::current.end(), fromPtr, toPtr);
you are inserting fromPtr
copies of the value toPtr
(ie overload (3)). From your description, it appears you mean to use overload (4):
super::current.insert(super::current.end(), vec + pos, vec + to);
which copies elements from vec
to super::current
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.