c++ - Correct way to set the size of a std::vector -


from read, std::vector appropriate structure use when interfacing c function requiring contiguous memory byte array. wondering how can determine size of array in cases

i have written small sample program illustrate mean.

int main(int argc, char *argv[]) {     std::vector<unsigned char>v;     unsigned char p[1024];      sprintf((char*)&p[0], "%10d", 10);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     v.reserve(30);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     memcpy(&v[0], &p[0], 20);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     v.reserve(50);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     v.reserve(0);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     v.resize(20);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;     v.resize(0);     cout << "size: " << v.size() << " length: " << v.capacity() << endl;      return 0; } 

the output (not surprising):

size: 0 length: 0 size: 0 length: 30 size: 0 length: 30 size: 0 length: 50 size: 0 length: 50 size: 20 length: 50 size: 0 length: 50 

the reason why did is, because reserve buffer of size , pass memory socket via recv(). since have pass memory pointer, there no way vector size gets adjusted according recv returns. when received number of bytes smaller buffer, have thought can somehow adjust size of vector, when pass back, caller can v.size() , the number of elements aka returned receive.

when looked @ data above example, when using resize() size of buffer adjusted correctly, data gone. have copy memory individually new vector correct size? sounds unnecessary overhead me. or there way tell vector how many elements supposed hold?

you're doing things in wrong order.

  1. resize max size want buffer accept.
  2. store data (which must smaller vector size).
  3. resize real data size.

your problem of "disappearing data" because when copy data first time, vector has no size capacity (ie. pre-reserved memory without using hold data). when reserve again, size still 0 vector free optimize out data copy since knows must keep first size() elements (ie. 0).

in other words:

  • capacity() = how data put in vector without triggering reallocation.
  • size() = how data you're using (and vector keep only that data across reallocations)

what's more, accessing vector elements past current size() undefined behaviour (it may appear work integral types think happen uninitialized objects...). don't that.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -