Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a range of data from char array into a vector?

Tags:

c++

stdvector

I've read file contents into a char array, and then read some data of it into a vector. How can i copy a range of the char array into the vector? both vector and char array is the same type (unsigned char).

Current code goes 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?

like image 816
Newbie Avatar asked Jan 21 '11 11:01

Newbie


People also ask

How do you add an array to a vector?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.

Can I store an array in a vector?

There are two ways to store a two-dimensional array/vector: As a vector of vectors (or array of arrays) As a one-dimensional array, with a coordinate transform.


1 Answers

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

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

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

vec.assign(arr, arr+len);

However, reading your question I wondered why you would first read into a C array just to copy its content into a vector, when you could read into a vector right away. A std::vector<> is required to keep its data in one contiguous block of memory, and you can access this block by taking the address of its first element. Just make sure you have enough room 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 could also get the address of the first element by &*vec.begin(). However, note that with either method you absolutely must make sure there's at least one element in the vector. None of the two methods are required to check for it (although your implementation might do so for debug builds), and both will invoke the dreaded Undefined Behavior when you fail on this.

like image 170
sbi Avatar answered Oct 10 '22 19:10

sbi