expand size of vector passed as memory

2019-07-14 14:48发布

问题:

I am passing my vector to a function that expects a c array. It returns the amount of data it filled (similar to fread). Is there a way i can tell my vector to change its size to include the amount that function has passed in?

of course i make sure the vector has the capacity() to hold that amount of data.

回答1:

No, there is no supported way to "expand" a vector so it contains extra values that have been directly copied in. Relying on "capacity" to allocate non-sized memory that you can write to is definitely not something you should rely on.

You should ensure your vector has the required amount of space by resizing before calling the function and then resizing to the correct value afterwards. E.g.

vector.resize(MAX_SIZE);
size_t items = write_array(&(vec[0]), MAX_SIZE)
vector.resize(items);


回答2:

capacity tells you only how much memory is reserved, but it is not the size of the vector.

What you should do is resizes to maximum required size first:

vec.resize(maxSizePossible);
size_t len = cfunc(&(vec[0]));
vec.resize(len);


回答3:

hmm..
vector.resize(size);
?



回答4:

std::vector has a resize() method with the new size as its parameter. So simply calling it with the number returned by your function should be fine.



回答5:

std::back_inserter might be what you need. Assuming your input function is able to work with an iterator, pass it std::back_inserter(myvector). That will push_back everything written to the iterator, and implicitly resize the vector as necessary.



标签: c++ stl vector