+ 2
How to use operator to define array-slicing in C++ ?
Hi there, I want to use operator to define array slicing in C++ just like its equivalent in Python ( list slicing ). Now I don't know how to do it, can you help me ? How to fix errors and use proper syntax ? https://code.sololearn.com/c49oADUHmEyb/?ref=app
7 odpowiedzi
+ 5
You cannot define custom operators like `[:]`, you can only implement operators that already exist in C++. So a nice sytnax like arr[1:5:2] won't be possible.
That doesn't mean we can't be creative tho. :P How's this for a hack?
https://code.sololearn.com/ccGTNTUQDSjh/?ref=app
+ 1
Schindlabua oh EXCELLENT. now I'm learning new things.
+ 1
Oops I only saw this just now, sorry!
https://code.sololearn.com/cG8yemKE8uTG/?ref=app
Anyway, a couple things:
You forgot to pass the size parameter in your constructor (hence the int* to int conversion error, it was trying to call the second ctor)
When calling the second ctor, you need to create a new array yourself that you can fill. Keep in mind that you need to free this memory too, in the destructor, which I didn't do in the example
The assignment operator shouldn't return a new object (`merged`), rather it should modify the existing object. Because that's what assignment is about, you assign a new value to an existing object :) Your usecase is better solved with a normal function, or possibly operator+.
Hope that does something for ya :) I've patched your example so it compiles, you figure out the rest!
0
Schindlabua can you help me with this one ?
I'm stuck with it, I don't know the proper syntax.
https://code.sololearn.com/ce0APrrnPaKb/?ref=app
0
Ali_combination when you're initializing a and b DynamicArrays, you pass only one argument, so the second constructor DynamicArray(int size) is called, which takes int, and you're passing it an int*. Pass the size also
If you do this and comment the line arr1=arr2, program compiles. But this line calls the coredump error - maybe smth is to be changed in operator=.
I don't get what this operator intended to do here — rewrite the arr1 with contents of arr2?
0
Patrick the second ctor is supposed to be used for the second operator overloading, the plus operator. It is sum of number of elements in a and in b => new_size = size of a + size of b
Next step is to return a pointer that points to an array that includes elements of a and elements of b respectively.
About the first ctor, well, just like vector assignment. arr1 will have the same elements as arr2 has.
currently im stuck with the first step, the assignment operator. i don't understand how to solve it.
0
Schindlabua thank you I learned new things . I think i have to return a new array (or as you did, allocate a new array using dynamic allocation) because arrays are not resizeable. The problem lies in such a situation that the two arrays do not have the same size. Thank you once again 👍