+ 1

C++ arrays

In c++ if we have: int A [3] = {1,2,3} & int B [3] = {10,20,30} how can we have: int C [6] = {1,10,2,20,3,30} where C [6]={A0,B0,A1,B1,A2,B2}

14th May 2017, 2:32 AM
Huda Zaher
Huda Zaher - avatar
10 Respostas
+ 9
try this... int C[6]; for (int x = 0; x < 3; x += 2) { C[x] = A[x]; C[x + 1] = B[x]; }
14th May 2017, 2:52 AM
Fox
Fox - avatar
+ 9
vector<int> A = {1, 2, 3}; vector<int> B = {10, 20, 30}; vector<int> C; for (int x = 0; x < a.size(); x++) // build C.. { C.push_back(A[x]); C.push_back(B[x]); }
14th May 2017, 2:43 AM
Fox
Fox - avatar
+ 9
To implement vectors and required libraries etc.. put "#include <vector>" at the top of the program that you're doing this with.
14th May 2017, 2:47 AM
Fox
Fox - avatar
+ 9
sizeof paves way for hackers via buffer overflows.
14th May 2017, 4:32 PM
Fox
Fox - avatar
+ 1
thanks
14th May 2017, 2:54 AM
Huda Zaher
Huda Zaher - avatar
0
is that in c++?
14th May 2017, 2:44 AM
Huda Zaher
Huda Zaher - avatar
0
is there is another way?
14th May 2017, 2:47 AM
Huda Zaher
Huda Zaher - avatar
0
isn't there a way with just "iostream library" without victors?
14th May 2017, 2:52 AM
Huda Zaher
Huda Zaher - avatar
0
More dynamic solution: int A[] = {1, 2, 3}; int B[] = {10, 20, 30}; int sizeA = sizeof(A)/sizeof(*A); int sizeB = sizeof(B)/sizeof(*B); int sizeC = sizeA + sizeB; int *C = new int[sizeC]; for(int i=0; i<sizeA; i++) C[i*2] = A[i]; for(int i=0; i<sizeB; i++) C[i*2+1] = B[i]; // Output results to console. for(int i=0; i<sizeC; i++) cout << C[i] << endl;
14th May 2017, 5:40 AM
Zaur Kandokhov
Zaur Kandokhov - avatar
0
In accepted solution there is A.size() used, but author asked a solution without vectors.
15th May 2017, 3:22 AM
Zaur Kandokhov
Zaur Kandokhov - avatar