In: Computer Science
int main() { int ListDataSample1[] = { 1, 1, 1 }; int ListDataSample2[] = { 2, 2, 2 }; List<int> List1 = List<int>(ListDataSample2, 3); List<int> List2 = List<int>(ListDataSample2, 3);
cout << "List1 :" << List1 << endl; cout << "List2 :" << List2 << endl << endl; List1 += List2;
cout << "List1 :" << List1 << endl; cout << "List2 :" << List2 << endl << endl; system("pause"); return 0; } |
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
#include<iostream>
using namespace std;
//templated List class
template<typename T>
class List{
//array pointer to store data
T* arr;
//current number of elements
int size;
public:
//constructor taking an array pointer and size
List(T* _arr, int _size){
//initializing dynamic array
arr=new T[_size];
//copying size
size=_size;
//copying all elements from _arr to arr
for(int i=0;i<size;i++){
arr[i]=_arr[i];
}
}
//destructor to deallocate memory occupied by arr
~List(){
delete[] arr;
}
//overloaded << operator (defined outside the class)
template <typename T2>
friend ostream& operator << (ostream &out, const List<T2> &list);
//overloaded += operator method
List& operator +=(const List& other){
//creating a new array with enough capacity to store elements of both arrays
T* newArr=new T[size+other.size];
//copying elements of this array to newarr
for(int i=0;i<size;i++){
newArr[i]=arr[i];
}
//copying elements of other array to newarr
for(int i=0;i<other.size;i++){
newArr[i+size]=other.arr[i];
}
//destroying old array from this object
delete[] arr;
//replacing with new array
arr=newArr;
//updating size
size=size+other.size;
//returning this object
return *this;
}
};
//overloaded << operator to print the contents of a list
template<typename T2>
ostream& operator << (ostream &out, const List<T2> &list){
//looping and printing all elements of list separated by comma and space
//since this is a friend function of List class, it can access private elements of
//list class
for(int i=0;i<list.size;i++){
out<<list.arr[i];
if(i!=list.size-1){
out<<", ";
}
}
return out;
}
//no change is made to main method
int main()
{
int ListDataSample1[] = { 1, 1, 1 };
int ListDataSample2[] = { 2, 2, 2 };
List<int> List1 = List<int>(ListDataSample2, 3);
List<int> List2 = List<int>(ListDataSample2, 3);
cout << "List1 :" << List1 << endl;
cout << "List2 :" << List2 << endl
<< endl;
List1 += List2;
cout << "List1 :" << List1 << endl;
cout << "List2 :" << List2 << endl
<< endl;
system("pause");
return 0;
}
/*OUTPUT*/
List1 :2, 2, 2
List2 :2, 2, 2
List1 :2, 2, 2, 2, 2, 2
List2 :2, 2, 2