Hi Gurus,
I'm new to C++, but I have a small background in java. I want to convert the following java code to c++, but returning array is a big trouble for me. This code parses the header of a stream and manipulates it. Following is java code. I need the c++ code does the same thing: Thanks in advance.
public class JoinBytes
{
public static void main(String[] args)
{
byte[] a = {1,2,3,4,5,6};
byte[] b = {7,8,9};
byte[] sum = combineBytes(a, b);
for(int i=0; i<sum.length; i++)
{
System.out.println("Byte at position "+ i + " is: " + sum[i]);
}
}
static byte[] combineBytes(byte[] a, byte[] b)
{
int i=0;
byte[] result = new byte[a.length+b.length];
for(i=0; i<a.length; i++)
{
result[i] = a[i];
}
In C++, an array is just a sequence. Besides the type of the elements, nothing else is known, like the length for example. So in C/C++, whenever an array is used, it's length must be passed too. By convention, C strings have a sentinel entry (NULL) to indicate the end, but if this is missing, you get a buffer overrun (a source of hacks).
That's where STL collections come in. They know everything they need to know to get the job done, like the length for example.
As per your advice I used vectors and the problem is solved. But I have to change all the dependent codes to accept the vector. Following is the same code done with vectors:
vector<byte> joinBytes(vector<byte> b1, vector<byte> b2)
{
vector<byte> tot;
int i = 0;
for(i=0; i<b1.size(); i++){
tot.push_back(b1[i]);
}
int main(int argc, char *argv[])
{
vector<byte> a1(2,5);
vector<byte> a2(10,12);
vector<byte> combined;
combined=joinBytes(a1, a2);
cout<<"Size of a1 is: "<<a1.size()<<endl;
cout<<"Size of a2 is: "<<a2.size()<<endl;
for (int i=0; i<combined.size(); i++)
cout << (short)combined[i]<<endl;
cout<<"The size of combined array is: "<<combined.size()<<endl;
It's conventional to pass in your collections by const reference if they don't need to be changed. const to enforce read-only operations, reference to not copy the collection.