How can I insert the content of arrays into a vector?
15,685
Solution 1
Assuming you know the size, you can insert a range:
vector.insert(vector.end(), buffer, buffer + size);
There's also a more generic algorithm for this sort of thing:
#include <iterator>
#include <algorithm>
std::copy(buffer, buffer + size, std::back_inserter(vector));
Solution 2
You can use std::begin
and std::end
(#include <iterator>
) to get begin and end iterators of the array :
vector.insert(vector.begin(), std::begin(buffer), std::end(buffer))
Solution 3
How about increasing the vector size by the required amount, and doing a memcpy?
Related videos on Youtube
Author by
user3378689
Updated on September 21, 2022Comments
-
user3378689 over 1 year
I need to write some simple code with
std::vector
s and I am struggling a bit.I have a
char[]
buffer that is filled with callback data from another program. I need to append this data to the end of a vector - the whole buffer.std::vector<char> vector; // data comes from another program void callback(char buffer[], size_t size) { // copy buffer to the end of vector here }
At the end the vector is supposed to contain continuous data from the buffer.
Is there an effective way to do this without inserting element by element with a loop?
for (size_t i = 0; i < size; ++i) vector.push_back(buffer[i]);
-
hivert about 10 yearsHow do you know the size of the buffer ? Or if it's not completely filled, how many character there are ?
-
n. m. about 10 yearsSearch keywords: std::copy, std::back_inserter.
-
-
Mike Seymour about 10 years
begin
andend
only work ifbuffer
is an array (not a pointer). It probably won't be here (although, without seeing the callback arguments, I can't be 100% sure). -
Mike Seymour about 10 yearsThat would probably be less efficient than
insert
orstd::copy
, since it would zero-initialise the new elements before copying over them. (It would also be more verbose, and less generic sincememcpy
only works for trivial types). -
Bgie about 10 yearsAgreed, using the standard library is better