Initializing a vector<BYTE> from existing BYTE array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blueflyy
    New Member
    • Sep 2007
    • 5

    #1

    Initializing a vector<BYTE> from existing BYTE array

    Hello,

    I wish to initialize a vector<BYTE> from an existing BYTE array.

    Simple example:

    Code:
    BYTE buf[] = {0,1,2,3,4,5};
    std::vector<BYTE> vec(buf, buf + sizeof(buf)/sizeof(buf[0]));
    This sample works and does what I asked for. The only difference is that it copies the buffer. I want the vector to point to the original BYTE array and not allocate+copy it.
    The reason behind this is because I have an old API that sends me a BYTE array (that was read from a file) and I want it in a vector. I can't afford duplicating the BYTE array that I receive because it can get to huge sizes.

    Thanks.
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by blueflyy
    Hello,

    I wish to initialize a vector<BYTE> from an existing BYTE array.

    Simple example:

    Code:
    BYTE buf[] = {0,1,2,3,4,5};
    std::vector<BYTE> vec(buf, buf + sizeof(buf)/sizeof(buf[0]));
    This sample works and does what I asked for. The only difference is that it copies the buffer. I want the vector to point to the original BYTE array and not allocate+copy it.
    The reason behind this is because I have an old API that sends me a BYTE array (that was read from a file) and I want it in a vector. I can't afford duplicating the BYTE array that I receive because it can get to huge sizes.

    Thanks.
    I think whenever you push an element to the vector it allocates and copies the object.
    Maybe other members can add to this
    Raghuram

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by blueflyy
      The reason behind this is because I have an old API that sends me a BYTE array (that was read from a file) and I want it in a vector. I can't afford duplicating the BYTE array that I receive because it can get to huge sizes.
      This is a contradiction. You can't use a vector to manage an array that's not in the vector.

      Also, I don't understand your duplication problem. The BYTE array is on the heap so you copy it to a vector<BYTE> that's also on the heap and then delete the BYTE array.

      That is, unless you are using the stack, which is a no-no in C++.

      What is "huge" anyway ??

      Comment

      Working...