From what i know a vector is guaranteed to be continuous and i can write a chunk of memory to it and do send of fwrite with it. All i need to do is make sure i call .resize() to force it to be the min length i need then i can use it as a normal char array? would this code be correct
v.resize(numOfElements); v.clear(); //so i wont get numOfElements + len when i push back vector<char>v2; v2.resize(numOfElements*SizeOfType); while(...) { ... v.push_bacK(x); } compress(&v2[0], len, &v[0], len); fwrite(&v2[0], ....)
noting that i never push back or pop v2 i only resize it once and used it as a char array. Would this be safe? and if i also dumped v that would also be safe(i do push back and clear, i may dump it for testing)
Well, that above code snippet is in effect allocating and creating elements, just to destroy them again. It’s in effect the same as:
Just that this code is way faster. So,
v.size() == 0in both cases andv.capacity()might be the same asnumOfElementsin both cases too (although this is not guaranteed). In the second case, however, the capacity is at least numOfElements, which means the internal buffer will not be reallocated until you have push_back’ed that many elements to your vector. Note that in both cases it is invalid if you try accessing any elements – because there are zero elements actually contained.Apart from that, i haven’t figured a problem in your code. It’s safe and i would encourage it so use it instead of a raw
newormallocbecause of the added safeties it provides. I’m however not sure what you mean by ‘dump v’.