c++ - std::vector insert not behaving as I would expect. Is it a bug? -


i have been using std::vector store binary data read file, serialized data gram sent on socket. wrote unittest end-to-end functionality failed unexpected reasons:

std::vector<char> buf; response->data(buf); assert(1 == buf.size()); 

the idea transfer 1 byte , receive 1 byte. got 4 bytes.

essentially happened insert event used in both encoding , decoding, resized vector bufsize * 2 bytes or chars. didn't see in documentation anywhere.

unsigned long sourcelen = 1; char source[] = { '0' };  ...  std::vector<char> buf; buf.resize(sourcelen); buf.insert(buf.begin(), source, source + sourcelen); assert(1 == buf.size());  // fails: buf.size() == 2. 

this happens again @ receiving end in decode method , results in buffer of 4 bytes. solved issue not using insert method , instead implementing c style loop:

buf.resize(sourcelen); (unsigned long = 0; < sourcelen; ++) {     buf[i] = source[i]; } assert(1 == buf.size());  // succeeds: buf.size() == 1. 

so why insert resize vector in such way end more data started with? oh, did try this, solved buffer size issue, resulted in no data being copied:

buf.resize(sourcelen); buf.insert(buf.begin(), data, data + datalen - 1);  assert(1 == buf.size());  // succeeds: buf.size() == 1. assert(buf[0] == source[0]);  // fails: buf[0] == ''. 

as case, had thought after submitted question. case insert retaining current contents , inserting new values? i.e. resize of vector should resize 0 bytes before calling insert?

update:

i missed in documentation...

the vector extended inserting new elements before element @ specified position, increasing container size number of elements inserted. 

std::insert() inserts new values , relocates old values. behaviour described expected. should use std::copy() instead.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -