tags:

views:

228

answers:

6

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.

A: 

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.

So you already solved it?

PoweRoy
Nope, capacity() doesn't solve it
jalf
You say that you resize the vector so capacity() returns the correct value. So you solved it.
PoweRoy
i asked the q, and no bc the len is what is retiurned from the func, .size() is not the size i want (rightnow its 1 always). I'll go with andrews answer.
acidzombie24
+1  A: 

hmm..
vector.resize(size);
?

shoosh
+2  A: 

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);
peterchen
+1  A: 

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.

Benoît
+7  A: 

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);
Andrew Grant
A: 

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.

jalf