C/C++

Программирование на С++

Напишите классы, реализующие тип данных. Перегрузите для них заданные операции. Протестируйте работу написанных классов. Перегрузите операторы: «+» – добавление элемента в множество, «-» – удаление элемента из множества, «>» – проверка на принадлежность элемента множеству, «==» – сравнение на равенство, «!=» – сравнение на неравенство, «^» – получение множества из элементов, встречающихся либо в одном либо в другом множестве, но не встречающихся в обоих, «!*» – проверка, что множества не имеют общих элементов. (Множества с элементами типа char.)
Напоминаю, что перегрузить можно только существующие операторы! Оператора «!*» не существует! Поэтому я перегрузил вместо него оператор «&». Если что-то не нравится, перегрузите другое :)

#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;
class Set {
public:
Set() = default;
explicit Set(const string& str) {
for (auto ch : str) box.insert(ch);
}
explicit Set(const char* str) {
for (int i = 0; str[i]; ++i) box.insert(str[i]);
}
void operator+(const char ch) {
box.insert(ch);
}
void operator-(const char ch) {
box.erase(ch);
}
bool operator>(const char ch)const {
return box.contains(ch);
}
bool empty()const {
return box.size() == 0;
}
private:
set<char> box;
friend bool operator==(const Set& a, const Set& b) {
return a.box == b.box;
}
friend bool operator!=(const Set& a, const Set& b) {
return a.box != b.box;
}
friend bool operator&(const Set& a, const Set& b) {
vector<char> acc;
set_intersection(
a.box.begin(), a.box.end(),
b.box.begin(), b.box.end(),
back_inserter(acc)
);
return acc.size() == 0;
}
friend Set operator^(const Set& a, const Set& b) {
vector<char> acc;
set_difference(
a.box.begin(), a.box.end(),
b.box.begin(), b.box.end(),
back_inserter(acc)
);
Set set;
for (auto ch : acc) set + ch;
return set;
}
friend ostream& operator<<(ostream& out, const Set& set) {
for (auto ch : set.box) cout.put(ch);
return out;
}
};
int main() {
cout << "Set 1: ";
string seq1;
getline(cin, seq1);
Set set1(seq1);
set1 + 'a';
cout << "Set 1: " << set1 << '\n';
set1 - 'b';
cout << "Set 1: " << set1 << '\n';
cout << "Symbol includes? ";
char c = cin.get();
cin.ignore(cin.rdbuf()->in_avail());
if (set1 > 'c') puts("Includes!");
else puts("Not includes!");
cout << "Set 2: ";
string seq2;
getline(cin, seq2);
Set set2(seq2);
if (set1 == set2) puts("Are equal!");
if (set1 != set2) puts("Not equal!");
auto set3 = set1 ^ set2;
if (!set3.empty()) cout << "Set 3: " << set3 << '\n';
else puts("Various elements are missing!");
if (set1 & set2) puts("There are no common elements!");
else puts("Common elements are available!");
}
Тимур Ибрагимов
Тимур Ибрагимов
98 246
Лучший ответ