Reputation: 539
#include <iostream>
using std::cout;
using std::cin;
struct Array {
int *A;
int size;
int length;
};
void display(Array *arr) {
for(int i = 0; i < arr->length; i++) {
cout << arr->A[i] << "\t";
}
cout << "\n";
}
Array* merge(Array *arr, Array *brr) {
Array *crr;
crr->length = 0;
crr->size = arr->length + brr->length;
crr->A = new int[crr->size];
int i, j, k; i=j=k=0;
while(i < arr->length && j < brr->length) {
if (arr->A[i] < brr->A[j]) {
crr->A[k++] = arr->A[i++];
} else {
crr->A[k++] = brr->A[j++];
}
}
for(;i < arr->length; i++) {
crr->A[k++] = arr->A[i];
}
for(;j < brr->length; j++) {
crr->A[k++] = brr->A[j];
}
crr->length = arr->length + brr->length;
return crr;
}
int main() {
Array arr1 = {{ 2, 6, 10, 15, 25}, 10, 5};
Array arr2 = {{ 3, 4, 7, 18, 20}, 10, 5};
Array *arr3;
arr3 = merge(&arr1, &arr2);
display(arr3);
}
Compiling this gives me this error. What is the right way to do this ?
$ g++ -o merge_arrays merge_arrays.cpp
merge_arrays.cpp: In function ‘int main()’:
merge_arrays.cpp:42:42: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘int*’ in initialization
42 | Array arr1 = {{ 2, 6, 10, 15, 25}, 10, 5};
| ^
merge_arrays.cpp:43:41: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘int*’ in initialization
43 | Array arr2 = {{ 3, 4, 7, 18, 20}, 10, 5};
| ^
I am initialising it at the same place I declare the struct Array
. Isnt this the recommended way ? I read many stackoverflow answers recommending me to initialise arrays at the same place where I declare them. This is exactly what I do here. So a bit confused. Any help would be greatly appreciated.
Upvotes: 2
Views: 3229
Reputation: 217275
With owning raw pointer, it would be:
Array arr1 = {new int[10]{ 2, 6, 10, 15, 25}, 10, 5};
but your class doesn't respect rules of 3/5/0 and leak resource.
But standard already provides std::vector
to handle collection and std::merge
:
void display(const std::vector<int>&v) {
for(int e : v) {
cout << e << "\t";
}
cout << "\n";
}
std::vector<int> merge(const std::vector<int>&v1, const std::vector<int>&v2)
{
std::vector<int> res(v1.size() + v2.size());
std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), res.begin());
return res;
}
int main() {
std::vector arr1 = { 2, 6, 10, 15, 25};
std::vector arr2 = { 3, 4, 7, 18, 20};
auto arr3 = merge(arr1, arr2);
display(arr3);
}
Upvotes: 4