Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- template <class T>
- class Item{
- protected:
- T *contents;
- int capacity, size;
- public:
- Item(int = 10);
- ~Item();
- int getSize();
- int getCapacity();
- bool isPresent(T);
- bool isFull();
- };
- template <class T>
- Item<T>::Item(int capacity){
- contents = new T[Item<T>::capacity = capacity];
- size = 0;
- }
- template <class T>
- Item<T>::~Item(){
- delete[] contents;
- }
- template <class T>
- bool Item<T>::isPresent(T item){
- int pos = -1;
- for(int i = 0; i < size; i++){
- if(contents[i] == item){
- pos = i;
- break;
- }
- }
- return pos != -1;
- }
- template <class T>
- bool Item<T>::isFull(){
- return size == capacity;
- }
- template <class S>
- class Set:public Item<S>{
- public:
- Set(int = 1);
- Set(int , int);
- Set(const Set<S>&);
- void read();
- void add(S);
- void display();
- Set<S>& operator =(const Set<S>&);
- Set<S> operator +(const Set<S>&);
- };
- template <class S>
- void Set<S>::display(){
- for(int i = 0; i < Item<S>::size; i++){
- cout << Item<S>::contents[i] << " ";
- }
- cout << endl;
- }
- template <class S>
- Set<S>::Set(int capacity):Item<S>(capacity){ }
- template <class S>
- Set<S>::Set(int capacity, int size):Item<S>(capacity){
- Item<S>::size = size;
- }
- template <class S>
- Set<S>::Set(const Set<S> &obj){
- Item<S>::contents = new S[obj.capacity];
- Item<S>::capacity = obj.capacity;
- Item<S>::size = obj.size;
- for(int i = 0; i < obj.size; i++){
- Item<S>::contents[i] = obj.contents[i];
- }
- }
- template <class S>
- Set<S>& Set<S>::operator =(const Set<S> &obj){
- Item<S>::size = obj.size;
- Item<S>::capacity = obj.capacity;
- for(int i = 0; i < obj.size; i++){
- Item<S>::contents[i] = obj.contents[i];
- }
- return *this;
- }
- template <class S>
- Set<S> Set<S>::operator +(const Set<S> &obj){
- Set<S> temp(obj.capacity + Item<S>::capacity);
- // Copying from the current object
- for(int i = 0; i < Item<S>::size; i++){
- temp.add(Item<S>::contents[i]);
- }
- // Copying from the obj object
- for(int i = 0; i < obj.size; i++){
- temp.add(obj.contents[i]);
- }
- return temp;
- }
- template <class S>
- void Set<S>::read(){
- cout << "Input values to set\n";
- cout << "Enter -1 to stop reading\n";
- int input;
- while(!Item<S>::isFull() ){
- cout << "Enter value: ";
- cin >> input;
- if(input == -1){
- break;
- }
- else{
- add(input);
- }
- }
- }
- template <class S>
- void Set<S>::add(S item){
- if(!Item<S>::isFull() && !Item<S>::isPresent(item)){
- Item<S>::contents[Item<S>::size] = item;
- Item<S>::size = Item<S>::size + 1;
- }
- }
- int main() {
- Set<int> s1(5);
- Set<int> s2(7);
- Set<int> s3;
- s1.read();
- s2.read();
- // Union operation
- s3 = s1 + s2;
- cout << "s1\n";
- s1.display();
- cout << "s2\n";
- s2.display();
- cout << "s3\n";
- s3.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment