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?

Share:
15,685

Related videos on Youtube

user3378689
Author by

user3378689

Updated on September 21, 2022

Comments

  • user3378689
    user3378689 over 1 year

    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]);
    
    • hivert
      hivert about 10 years
      How do you know the size of the buffer ? Or if it's not completely filled, how many character there are ?
    • n. m.
      n. m. about 10 years
      Search keywords: std::copy, std::back_inserter.
  • Mike Seymour
    Mike Seymour about 10 years
    begin and end only work if buffer 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
    Mike Seymour about 10 years
    That would probably be less efficient than insert or std::copy, since it would zero-initialise the new elements before copying over them. (It would also be more verbose, and less generic since memcpy only works for trivial types).
  • Bgie
    Bgie about 10 years
    Agreed, using the standard library is better