Question

creat a template in c++ that, given an array of elements of any template type, deletes...


creat a template in c++ that, given an array of elements of any template type, deletes an element on a given position
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//code

#include<iostream>

using namespace std;

//template method to remove the element at given index in an array

//index - index of item to remove

//elements - array

//size - current number of elements in array

template<typename T>

void removeElementAt(int index, T elements[], int &size){

                //validating index

                if(index>=0 && index<size){

                                //starting at index 'index', shifting all elements to left once to occupy

                                //the vacant space

                                for(int i=index;i<size-1;i++){

                                               elements[i]=elements[i+1];

                                }

                                //decrementing size by 1

                                size--;

                }

               

}

int main(){

                //testing

                int arr[]={1,2,3,4,5,6,7,8,9};

                int size=9;

                int pos=3;

                removeElementAt(pos, arr, size);

                for(int i=0;i<size;i++){

                                cout<<arr[i]<<" "; //should be 1 2 3 5 6 7 8 9

                }

                cout<<endl;

               

                string arr2[]={"a","b","c","d"};

                size=4;

                pos=0;

                removeElementAt(pos, arr2, size);

                for(int i=0;i<size;i++){

                                cout<<arr2[i]<<" "; //should be b c d

                }

                cout<<endl;

               

                return 0;

}

//output

1 2 3 5 6 7 8 9

b c d

Add a comment
Know the answer?
Add Answer to:
creat a template in c++ that, given an array of elements of any template type, deletes...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT