Increase the size of the vector passed as memory

I pass my vector to a function that expects an array of c. It returns the amount of data populated (similar to fread). Is there a way I can pass my vector to resize it to include the amount the function went into?

of course, I make sure that the vector has the ability () to hold this amount of data.

+2
c ++ vector stl
source share
5 answers

No, there is no supported way to "expand" the vector, so it contains additional values ​​that were directly copied. Relying on the “capacity” for allocating non-dimensional memory that you can write is definitely not what you need to rely on.

You must make sure that your vector has the required space by resizing it before calling the function, and then resizing it to the desired value. For example.

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

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

What you have to do, first resize to maximum size:

 vec.resize(maxSizePossible); size_t len = cfunc(&(vec[0])); vec.resize(len); 
+2
source share

hmm ..
vector.resize(size);

+1
source share

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

+1
source share

std::back_inserter may be what you need. Assuming your input function can work with an iterator, pass it to std::back_inserter(myvector) . This will push_back everything written on the iterator, and implicitly resize the vector as needed.

0
source share

All Articles