Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert the content of arrays into a vector?

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]);
like image 837
user3378689 Avatar asked Apr 22 '14 09:04

user3378689


People also ask

How do you input an array into 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

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));
like image 189
Mike Seymour Avatar answered Oct 20 '22 00:10

Mike Seymour