How to copy data range from char array to vector?

I read the contents of the file into a char array and then read some data about it into a vector. How can I copy the range of a char array to a vector? both vector and char are the same type (unsigned char).

The current code looks something like this:

int p = 0; for(...){ short len = (arr[p+1] << 8) | arr[p+0]; p+=2; ... for(...len...){ vec.push_back(arr[p]); p++; } } 

I would like to improve this by dropping the loop with push_back , How?

+6
c ++ stdvector
source share
1 answer

Adding something to a vector can be done using the insert() member function:

 vec.insert(vec.end(), arr, arr+len); 

Of course, there is also assign() , which is probably closer to what you want to do:

 vec.assign(arr, arr+len); 

However, after reading your question, I wondered why you first read into the C array only to copy its contents into a vector when you could read the text immediately. A std::vector<> is required to store its data in one continuous block of memory, and you can access this block by taking the address of your first element. Just make sure you have enough space in the vector:

 std::size_t my_read(char* buffer, std::size_t buffer_size); vec.resize( appropriate_length ); vec.resize( my_read_func(&vec[0], vec.size()) ); 

Instead of &vec[0] you can also get the address of the first element &*vec.begin() . However, note that with any method you absolutely must make sure that there is at least one element in the vector . Neither of these two methods is required for verification (although your implementation can do this for debug builds), and both will cause scary Undefined behavior when you work.

+17
source share

All Articles