HEY I HAVE A DOUBT IN ONE OOPS QUESTION, HERE THE CLASS IS VEC AND THE DATA NUMBER IS ARR[100] AND THEIR FUNCTION IS V.LENGTH AND V.CAPACITY AND WE HAVE TO DOUBLE THE SIZE OF THE ARRAY WHEN THE ARRAY FILLED BY HALF OF ITS SIZE.
Oops doubt question
CAN YOU GIVE ME THE HINT HOW TO CODE THIS.
@Ayushi21
Make these variables in private
int *arr ; // pointer to int so we can make array dynamically , this would allow us to increase the size during runtime
int size ; // length of array
int capacity ; // capacity of array
Make a constructor which initializes each of them. Make size and capacity as 0 or 1 initially , whatever you wish.
Make length and capacity functions with int return type which simply return the value of size and capacity respectively.
As for the push_back( ) , this function should allow us to push data at the end of the array. In the push_back( ) , First check if (size+1) <= capacity/2 , if it is then you can add the new element at the end of array and just increment size.
Else , we need to increase the size of our array. In order to do that , make another pointer , say oldArray and put it equal to arr. Reallocate memory to arr which is twice the original capacity i.e.
int * oldArray = arr ;
arr = new int [ capacity*2] ;
Now your old data is in the oldArray and you have a new array with twice the capacity. Copy the data from oldArray and then delete it using the delete operator.
Make capacity = capacity *2 as we just doubled our array capacity.
Now push the new data inside the arr as we have enough space now. Increment size by 1.
Try writing a pop function and if you have done operator overloading , try overloading the square brackets operator [ ] to find and access any element in the array. Let me know if you need any help.
hello i have done the code till how much i understood. can you please check my code. https://ide.codingblocks.com/s/101945 – this is the url of the code
@Ayushi21
push_back should have a void return type.
It should take one int value as an argument which it pushes at the end of the array after the sizing process.
can you tell me what should be the output.
@Ayushi21
Input and output isn’t really our concern for this program. We are just trying to make our own class which can adapt to our needs. It’s the code that matters here.
If you want to check it through input and output then you may write a simple read and write output program. That is , take a number n as input and then read n integers and store them in your Vec object and then simply print the array using a loop. Add the elements using push_back function and read them using another function or better through the overloaded square bracket [ ] operators.