Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 28.05.2010, 13:02   #1
Танюня
 
Регистрация: 28.05.2010
Сообщений: 6
Стрелка C++ Класс множество целых чисел

Здраствуйте, дорогие)
Пришла к вам за помощью, ибо в программировании я не сильна. А задание у меня следующее.

Определить классы, написать main для проверки работы классов main и реализация классов должны быть отдельными модулями, описание классов - в .h файле

В случае невозможности выполнить действия должны порождаться исключительные ситуации.
Также должны предусмотрены необходимые конструкторы и деструкторы, определена операция присваивания.


Класс множество целых чисел (числа различны)
Методы и операции:
  • пересечение двух множеств (*)
  • объединение двух множеств (+)
  • разность двух множеств (-)
  • добавить элемент в множество
  • удалить элемент из множества
  • входит элемент в множество?
  • два множества равны (==)
  • является подмножеством
  • количество элементов в множестве
  • ввод и вывод в поток

заранее премногоблагодарна)
Танюня вне форума Ответить с цитированием
Старый 15.06.2010, 13:51   #2
Танюня
 
Регистрация: 28.05.2010
Сообщений: 6
По умолчанию

Вот что получилось у самой

Код:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

class Array
{
   int *mas,k;
   void Add(int);
   void Sub(int);
public:
   Array():k(0),mas(new int[0]) {};
   Array(const Array &);
   ~Array() {delete[]mas;};
   void operator+=(int n) {Add(n);};
   void operator+=(Array &);
   void operator-=(int n) {Sub(n);};
   void operator-=(Array &);
   void operator*=(Array &);
   friend bool operator==(Array &, Array &);
   friend bool operator<=(Array &, Array &);
   friend ostream& operator<<(ostream &, const Array &);
   friend istream& operator>>(istream &s, Array &);
   int HowMany() {return k;};
};

Array::Array(const Array &x):k(x.k),mas(new int[k])
{
   for(int i=0;i<k;i++)
      mas[i]=x.mas[i];
}

void Array::Add(int n)
{
   int *t,pos;
   for(pos=0;pos<k && mas[pos]<n;pos++) {}
   if (mas[pos]!=n)
   {
      t=new int[++k];
      for(int i=0;i<k-1;i++)
      t[i<pos?i:i+1]=mas[i];
      t[pos]=n;
      delete[]mas;
      mas=t;
   }
}

void Array::operator+=(Array &x)
{
   for(int i=0;i<x.k;i++)
      Add(x.mas[i]);
}

void Array::Sub(int n)
{
   if (k>0)
   {
      int *t,pos;
      for(pos=0;pos<k && mas[pos]<n;pos++) {}
      if (mas[pos]==n)
      {
         t=new int[--k];
         for(int i=0;i<k+1;i++)
         if (i!=pos) t[i<pos?i:i-1]=mas[i];
         delete[]mas;
         mas=t;
      }
   }
}

void Array::operator-=(Array &x)
{
   for(int i=0;i<x.k;i++)
      Sub(x.mas[i]);
}

void Array::operator*=(Array &x)
{
   Array t(*this);
   t-=x;
   for(int i=0;i<t.k;i++)
      Sub(t.mas[i]);
}

bool operator==(Array &x, Array &y)
{
   if (x.k!=y.k) return false;
   for (int i=0;i<x.k;i++)
   if (x.mas[i]!=y.mas[i]) return false;
   return true;
}

bool operator<=(Array &x, Array &y)
{
   int s=0;
   for (int i=0;i<x.k;i++)
   while(x.mas[i]!=y.mas[i+s])
   {
      if (x.k+s>y.k) return false;
      s++;
   }
   return true;
}

ostream &operator<<(ostream &s, const Array &p)
{ 
   s<<"(";
   for (int i=0;i<p.k-1;i++)
      s<<p.mas[i]<<",";
   return s<<p.mas[p.k-1]<<")";
}
istream &operator>>(istream &s, Array &p)
{
  int i;
  char c;
  s>>c;
  for (i=0;i<p.k-1;i++)
  {
  while (c!=')')
    s>> p.mas[p.k-1]>> c;
    }
    return s;
  
  }
int main()
{
   Array a,b;
   cin>>a;
   
   cout<<a<<"\n";
   a+=9;
   cout<<a<<"\n";
   b+=5;
   b+=7;
   b+=9;

   cout<<a<<"\n"<<b<<"\n"<<b.HowMany()<<"\n";
   return 1;
}


istream не работает. помогите

Последний раз редактировалось Stilet; 15.06.2010 в 14:26.
Танюня вне форума Ответить с цитированием
Старый 15.06.2010, 14:29   #3
Stilet
Белик Виталий :)
Старожил
 
Аватар для Stilet
 
Регистрация: 23.07.2007
Сообщений: 57,097
По умолчанию

VS2010Beta
Добавил system("pause");перед return в main()

Получил:
Цитата:
3
(-33686019)
(9)
(9)
(5,7,9)
3
Для продолжения нажмите любую клавишу . . .
Все норм работает.
I'm learning to live...
Stilet вне форума Ответить с цитированием
Старый 15.06.2010, 18:38   #4
Танюня
 
Регистрация: 28.05.2010
Сообщений: 6
По умолчанию

переделала. теперь не работает разница множеств. вот код

Код:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

class Array
{
   int *mas,k;
   void Add(int);
   void Sub(int);
public:
   Array():k(0),mas(new int(0)) {};
   Array(const Array &);
   ~Array() {delete[]mas;};
   void operator+=(int n) {Add(n);};
   void operator+=(Array &);
   void operator-=(int n) {Sub(n);};
   void operator-=(const Array &);
   Array operator*(const Array &)const;
   void operator*=(const Array &);
   friend bool operator==(Array &, Array &);
   friend bool operator<=(Array &, Array &);
   friend ostream& operator<<(ostream &, const Array &);
   friend istream& operator>>(istream &s, Array &);
   int HowMany() {return k;};
};

Array::Array(const Array &x):k(x.k)
{
   mas=new int[k];
   for(int i=0;i<k;i++)
      mas[i]=x.mas[i];
}

void Array::Add(int n)
{
   int *t,pos;
   for(pos=0;pos<k && mas[pos]<n;pos++) {}
   if (mas[pos]!=n)
   {
      t=new int[++k];
      for(int i=0;i<k-1;i++)
      t[i<pos?i:i+1]=mas[i];
      t[pos]=n;
      delete[]mas;
      mas=t;
   }
}

void Array::operator+=(Array &x)
{
   for(int i=0;i<x.k;i++)
      Add(x.mas[i]);
}

void Array::Sub(int n)
{
   if (k>0)
   {
      int *t,pos;
      for(pos=0;pos<k && mas[pos]<n;pos++) {}
      if (mas[pos]==n)
      {
         t=new int[--k];
         for(int i=0;i<k+1;i++)
         if (i!=pos) t[i<pos?i:i-1]=mas[i];
         delete[]mas;
         mas=t;
      }
   }
}

void Array::operator-=(const Array &x)
{
   for(int i=0;i<x.k;i++)
      return Sub(x.mas[i]);
}

Array Array::operator*(const Array &x)const
{
   Array t(*this),t2(*this);
   t-=x;
   for(int i=0;i<t.k;++i)
      t2.Sub(t.mas[i]);
      return t2;
}

void Array::operator*=(const Array &x)
{
   Array t(*this);
   t-=x;
   for(int i=0;i<t.k;i++)
      Sub(t.mas[i]);
}

bool operator==(Array &x, Array &y)
{
   if (x.k!=y.k) return false;
   for (int i=0;i<x.k;i++)
   if (x.mas[i]!=y.mas[i]) return false;
   return true;
}

bool operator<=(Array &x, Array &y)
{
   int s=0;
   for (int i=0;i<x.k;i++)
   while(x.mas[i]!=y.mas[i+s])
   {
      if (x.k+s>y.k) return false;
      s++;
   }
   return true;
}

ostream &operator<<(ostream &s, const Array &p)
{ 
   if (p.k!=0){
   s<<"(";
   for (int i=0;i<p.k-1;i++){
      s<<p.mas[i]<<",";
      }
      s<<p.mas[p.k-1];
      }
   return s<<")";
}
istream &operator>>(istream &s, Array &p)
{
  int tmp;
  char c;
  s>>c;
  
  while(c!=')')
  {
    s>>tmp>> c;
    p.Add(tmp);
    }
    return s;
  
  }

int main()
{
   Array a,b,c;
   cout<<" Введите множество А: "<<"\n";
   cin>>a;   
   cout<<a<<"\n";
   a-=9;
   cout<<"После вычитания из множества элемента 9: "<<a<<"\n";
   cout<<" Введите множество B: "<<"\n";
   cin>>b;  
   b+=7;
   cout<<"После добавления в множествo элементa 7 : "<<b<<"\n"; 
   cout<<" Пересечение множеств A и В: "<<"\n";
   cout<<a*b<<"\n";
   cout<<"Количество элементов в множестве В: "<<b.HowMany()<<"\n";
   if (a<=b)
      cout<<"А - подмножество В \n";
    else { if (b<=a)  
    cout<<"B - подмножество A \n";}
  cout<<" Объединение множеств А и B: "<<"\n";
     c=a;
     a+=b; 
   cout<<a<<"\n";
   cout<<" Разница множеств А и B: "<<"\n";
   c-=b;
   cout<<c<<"\n";
   return 1;
}

Последний раз редактировалось Stilet; 27.02.2011 в 16:30.
Танюня вне форума Ответить с цитированием
Старый 16.06.2010, 08:34   #5
Танюня
 
Регистрация: 28.05.2010
Сообщений: 6
По умолчанию

Переделала.
Теперь проблема с вычитанием.
Вот что получилось.

Код:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

class Array
{
   int *mas,k;
   void Add(int);
   void Sub(int);
public:
   Array():k(0),mas(new int(0)) {};
   Array(const Array &);
   ~Array() {delete[]mas;};
   void operator+=(int n) {Add(n);};
   void operator+=(Array &);
   void operator-=(int n) {Sub(n);};
   void operator-=(const Array &);
   Array operator*(const Array &)const;
   void operator*=(const Array &);
   friend bool operator==(Array &, Array &);
   friend bool operator<=(Array &, Array &);
   friend ostream& operator<<(ostream &, const Array &);
   friend istream& operator>>(istream &s, Array &);
   int HowMany() {return k;};
};

Array::Array(const Array &x):k(x.k)
{
   mas=new int[k];
   for(int i=0;i<k;i++)
      mas[i]=x.mas[i];
}

void Array::Add(int n)
{
   int *t,pos;
   for(pos=0;pos<k && mas[pos]<n;pos++) {}
   if (mas[pos]!=n)
   {
      t=new int[++k];
      for(int i=0;i<k-1;i++)
      t[i<pos?i:i+1]=mas[i];
      t[pos]=n;
      delete[]mas;
      mas=t;
   }
}

void Array::operator+=(Array &x)
{
   for(int i=0;i<x.k;i++)
      Add(x.mas[i]);
}

void Array::Sub(int n)
{
   if (k>0)
   {
      int *t,pos;
      for(pos=0;pos<k && mas[pos]<n;pos++) {}
      if (mas[pos]==n)
      {
         t=new int[--k];
         for(int i=0;i<k+1;i++)
         if (i!=pos) t[i<pos?i:i-1]=mas[i];
         delete[]mas;
         mas=t;
      }
   }
}

void Array::operator-=(const Array &x)
{
   for(int i=0;i<x.k;i++)
      return Sub(x.mas[i]);
}

Array Array::operator*(const Array &x)const
{
   Array t(*this),t2(*this);
   t-=x;
   for(int i=0;i<t.k;++i)
      t2.Sub(t.mas[i]);
      return t2;
}

void Array::operator*=(const Array &x)
{
   Array t(*this);
   t-=x;
   for(int i=0;i<t.k;i++)
      Sub(t.mas[i]);
}

bool operator==(Array &x, Array &y)
{
   if (x.k!=y.k) return false;
   for (int i=0;i<x.k;i++)
   if (x.mas[i]!=y.mas[i]) return false;
   return true;
}

bool operator<=(Array &x, Array &y)
{
   int s=0;
   for (int i=0;i<x.k;i++)
   while(x.mas[i]!=y.mas[i+s])
   {
      if (x.k+s>y.k) return false;
      s++;
   }
   return true;
}

ostream &operator<<(ostream &s, const Array &p)
{ 
   if (p.k!=0){
   s<<"(";
   for (int i=0;i<p.k-1;i++){
      s<<p.mas[i]<<",";
      }
      s<<p.mas[p.k-1];
      }
   return s<<")";
}
istream &operator>>(istream &s, Array &p)
{
  int tmp;
  char c;
  s>>c;
  
  while(c!=')')
  {
    s>>tmp>> c;
    p.Add(tmp);
    }
    return s;
  
  }

int main()
{
   Array a,b,c;
   cout<<" Введите множество А: "<<"\n";
   cin>>a;   
   cout<<a<<"\n";
   a-=9;
   cout<<"После вычитания из множества элемента 9: "<<a<<"\n";
   cout<<" Введите множество B: "<<"\n";
   cin>>b;  
   b+=7;
   cout<<"После добавления в множествo элементa 7 : "<<b<<"\n"; 
   cout<<" Пересечение множеств A и В: "<<"\n";
   cout<<a*b<<"\n";
   cout<<"Количество элементов в множестве В: "<<b.HowMany()<<"\n";
   if (a<=b)
      cout<<"А - подмножество В \n";
    else { if (b<=a)  
    cout<<"B - подмножество A \n";}
  cout<<" Объединение множеств А и B: "<<"\n";
     c=a;
     a+=b; 
   cout<<a<<"\n";
   cout<<" Разница множеств А и B: "<<"\n";
   c-=b;
   cout<<c<<"\n";
   return 1;
}

Последний раз редактировалось Stilet; 27.02.2011 в 16:30.
Танюня вне форума Ответить с цитированием
Старый 27.02.2011, 12:54   #6
Equive
Новичок
Джуниор
 
Регистрация: 27.02.2011
Сообщений: 2
По умолчанию

Что означает эта строчка?

t[i<pos?i:i+1]=mas[i];

Подскажите, пожалуйста!
Equive вне форума Ответить с цитированием
Старый 27.02.2011, 14:37   #7
Obey-Kun
Линуксоид
Участник клуба
 
Аватар для Obey-Kun
 
Регистрация: 31.07.2009
Сообщений: 1,403
По умолчанию

i<pos?i:i+1 использует тринарный оператор. Посмотрите в википедии.
Я схожу с ума или это глючит реальность?
Jabber ID: obey@obey.su
Obey-Kun вне форума Ответить с цитированием
Старый 27.02.2011, 16:21   #8
onewho
Форумчанин
 
Регистрация: 29.09.2010
Сообщений: 636
По умолчанию

странная у вас перегрузка +=, -=, *=

думаю, void Array:perator+=(Array &x) нужно заменить на Array Array:perator+=(Array &x) и возвращать *this;

перегрузка так
Код:
void Array::operator+=(Array &x)
{
for(int i=0;i<x.k;i++)
Add(x.mas[i]);
}
вообще удивила.
onewho вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Задан файл f1 целых чисел Andreu123 Паскаль, Turbo Pascal, PascalABC.NET 0 16.05.2010 15:18
массив целых чисел.... Ma666oT Помощь студентам 4 01.04.2010 17:13
массив целых чисел -ushёl- Помощь студентам 4 28.02.2009 19:18
массив целых чисел ^SPARTAK^ Паскаль, Turbo Pascal, PascalABC.NET 1 27.12.2008 10:59