C ++相当于Java的System.arraycopy [英] C++ equivalent to Java's System.arraycopy

查看:126
本文介绍了C ++相当于Java的System.arraycopy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的口,使大量使用System.arraycopy方法的一些Java code,想知道是否有在C等效++。基本上我想有n个字节数组并将它们合并成一个大阵。每个初始数组的长度可变的,所以我不想去通过计算高端阵列的长度,然后填充整个阵列的一个位置在同一时间,因为这感觉相当慢,我敢肯定,这的篮球操作已被优化。但是,我找不到这种优化是什么(虽然我可能使这个复杂得多,它应该是)。

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 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).

下面是一些伪(JAVA)code来说明什么,我想做的事情。

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}

就像我说的,这可能是C ++简单,但我会做这么多,多次想确保我尽可能高效做越好。

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.

推荐答案

由于a_len和b_len(含的字节长度和b),和一个dst缓冲区大足以容纳两个数组,你可以使用的memcpy。注意:这也取决于DST被声明为指针,以字节大小的数据

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 );

这非常适用于原始类型(因为它看起来像你复制字节数组左右)...如果你需要复制的对象,来看看的std ::复制和LT;>()

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<>().

这篇关于C ++相当于Java的System.arraycopy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆