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).

1 Answer
1

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:

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.

i need to read it into a buffer, because im reading data from same file at two different places at same time. this assign seems to work, except i had to do: vec.assign(arr+p, arr+p+len); (is this correct? at least it works)
–
NewbieJan 21 '11 at 11:39

2

@Newbie: Noone can tell if it's correct if you don't post the complete code ... your code in the OP is also so full of holes that you have to guess what you are trying to do.
–
etarionJan 21 '11 at 11:47

@etarion: really? that code i showed had everything important related to the arr[] array.
–
NewbieJan 21 '11 at 12:08

@Newbie: Whenever you can read into a C array, you can read into the vector right away.
–
sbiJan 21 '11 at 12:50

@sbi: I can't find any documentation for a std::vector append() member function. Is there such an animal?
–
BlastfurnaceJan 21 '11 at 15:51