Question

I need to write some simple code with std::vectors 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]);
Was it helpful?

Solution

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

OTHER TIPS

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

How about increasing the vector size by the required amount, and doing a memcpy?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top