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

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

问题描述

我试图移植我的一些Java代码,大量使用System.arraycopy方法,并想知道是否有一个等价的C ++。基本上我想有n字节数组,并将它们组合成一个大数组。每个初始数组可以是可变长度,所以我不想经历计算结束数组长度的箍,然后一次填充整个数组一个位置,因为这感觉相当缓慢,我敢肯定这操作已优化。但是,我找不到这个优化是什么(虽然我可能会使这更复杂,应该是)。



这里是一些伪(Java)我想要做的。

  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);
//现在,我希望ab看起来像{0x00,0x01,0x02,0x03,0x04,0x05}

像我说的,这可能是简单的在C + +,但我会做这很多,很多次,并希望确保我尽可能有效地做。

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

  memcpy(dst,a,a_len) 
memcpy(dst + a_len,b,b_len);

这对原始类型非常有用(因为它看起来像是复制字节数组) 。如果你需要复制对象,看看std :: copy<>()。


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

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

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

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