Matin Kh
Matin Kh

Reputation: 5178

Append a byte array to a string c++ efficiently

I am processing several chunks of byte arrays (uint_8) and append them to a string (my_string). For efficiency purposes, I have reserved more than enough bytes for my string by

my_string.reserve(more_than_enough_bytes);

I am trying to append each chunk as shown in the following function:

bool MyClass::AppendToMyString(uint_8* chunk, size_t chunk_num_bytes) {
  memcpy(const_cast<uint_8*>(my_string.data()), chunk, chunk_num_bytes);
  return true;
}

But the problem is that memcpy does not update my_string size. So, next time when this function is called, I do not where the last element was, other than using a separate variable for it. Any ideas?

Upvotes: 1

Views: 4802

Answers (1)

catnip
catnip

Reputation: 25408

std::string has an append method which will take care of this. Something along the lines of:

void append_chunk (std::string &s, const uint8_t* chunk, size_t chunk_num_bytes)
{
    s.append ((char *) chunk, chunk_num_bytes);
}

Live demo

Upvotes: 2

Related Questions