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]);
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With