Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- using namespace std;
- /*
- * Class of relation.
- * Main feature is to
- * check if it is reflexive.
- * (Relation is reflexive
- * if main diagonal of
- * matrix contains only 1)
- */
- class Relation
- {
- private:
- int **matrix; // Matrix of particular relation
- int size; // Size of relation matrix (number of elements in relation)
- public:
- // Main constructor
- Relation(int size);
- // Method to enter matrix of relation
- void input();
- // Getter to check if relation is reflexive using its matrix
- bool isReflexive();
- // Relation printing overloading
- friend ostream &operator<<(ostream &out, Relation relation);
- ~Relation();
- };
- Relation::Relation(int size)
- {
- this->size = size;
- this->matrix = new int *[size];
- for (size_t i = 0; i < size; i++)
- {
- matrix[i] = new int[size];
- for (size_t j = 0; j < size; j++)
- {
- matrix[i][j] = 0;
- }
- }
- cout << *this << endl;
- this->input();
- }
- void Relation::input()
- {
- cout << "Enter relation matrix:" << endl;
- for (size_t i = 0; i < this->size; i++)
- {
- for (size_t j = 0; j < this->size; j++)
- {
- int number;
- cin >> number;
- // Entered number validation
- if (number != 0 && number != 1)
- {
- cout << "Wrong number was entered: " << number << ", replaced by 1." << endl;
- number = 1;
- }
- this->matrix[i][j] = number;
- }
- }
- }
- bool Relation::isReflexive()
- {
- for (size_t i = 0; i < this->size; i++)
- {
- for (size_t j = 0; j < this->size; j++)
- {
- if (i == j)
- {
- if (this->matrix[i][j] != 1)
- {
- return false;
- }
- }
- }
- }
- return true;
- }
- ostream &operator<<(ostream &out, Relation relation)
- {
- out << "Matrix of relation:" << endl;
- for (size_t i = 0; i < relation.size; i++)
- {
- for (size_t j = 0; j < relation.size; j++)
- {
- out << setw(4) << relation.matrix[i][j];
- }
- if (i != relation.size - 1)
- {
- out << endl;
- }
- }
- return out;
- }
- Relation::~Relation()
- {
- for (size_t i = 0; i < this->size; i++)
- {
- delete[] this->matrix[i];
- }
- delete[] this->matrix;
- }
- int main()
- {
- int size;
- cout << "Enter relation size:" << endl;
- cin >> size;
- // Validating relation size
- if (size <= 0)
- {
- cout << "Wrong size." << endl;
- return 0;
- }
- cout << endl;
- Relation *relation = new Relation(size);
- cout << endl;
- cout << relation << endl;
- cout << "The relation is " << (relation->isReflexive() ? "" : "not ")
- << "reflexive." << endl;
- delete relation;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment