I'm trying to port some Java code of mine that makes heavy use of the System.arraycopy method and want to know if there is an开发者_如何学Go equivalent in C++. Basically I want to have n byte arrays and combine them into one big array. Each of the initial arrays can be of variable length, so I don't want to go through the hoops of calculating the end arrays length and then populating the entire array one position at a time as this feels rather slow and I'm sure this operation has been optimized. However, I can't find what this optimization is (although I may be making this more complicated than it should be).
Here's some pseudo (Java) code to illustrate what I want to do.
byte[] a = new byte[]{0x00, 0x01, 0x02};
byte[] b = new byte[][0x03, 0x04, 0x05];
byte[] ab = new byte[a.length+b.length];
System.arraycopy(ab, 0, a, 0, a.length);
System.arraycopy(ab, a.length+1, b, 0, b.length);
//Now, I would expect ab to look like {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}
Like I said, this may be simple in C++, but I will be doing this many, many times and want to make sure I'm doing it as efficiently as possible.
Given a_len and b_len (containing the length in bytes of a and b), and a dst buffer big enough to hold both arrays, you can use memcpy. Note: this also depends on dst being declared as a pointer to byte size data.
memcpy( dst, a, a_len );
memcpy( dst+a_len, b, b_len );
This works well for primitive types (as it looks like you're copying byte arrays around)... If you need to copy objects, take a look at std::copy<>().
Try this:
#include <vector>
int main()
{
typedef unsigned char Byte;
std::vector<Byte> a;
std::vector<Byte> b;
// Fill vectors a and b
std::vector<Byte> ab;
// Reserve enough memory to fit a and b in order to avoid
// unnecessary reallocations.
ab.reserve(a.size() + b.size());
ab.insert(ab.end(), a.begin(), a.end());
ab.insert(ab.end(), b.begin(), b.end());
return 0;
}
In C++, std::vector
is your friendly neighborhood dynamically re-sizable array. It is just as fast as regular arrays for random access. It is well worth the time to study std::vector
and other containers/algorithms in the standard library. I recommend the C++ standard library book by Josuttis.
vector::insert
on vectors of basic types will probably be just as fast as doing C-style memcpy
on C arrays. I'd be very surprised if it weren't.
精彩评论