Hi there,
I created my first class as an exercise from my textbook and I would appreciate any comment by you folks.
The exercise reads as follows:
Create a class "IntSet" consisting of two files: IntSet.h and IntSet.cpp. The class is supposed to represent a mathematical set for integers. Only the following simple operations should be possible:
-void add(int el): add element "el" if it is not already in the set, otherwise do nothing
-void remove(int el): remove element "el" if it is in the set, otherwise do nothing
-bool isMember(int el): report if element "el" is in the set or not
-size_t size(): return the number of elements
-void display(): write all elements to standard output
-void clear(): remove all elements from the set
-int getMax() and int getMin(): return the smallest and the biggest element in the set
To store the elements please us a vector<int> object.
And here is my solution so far:
IntSet.h
Code:
#ifndef SET_H
#define SET_H
#include <vector>
#include <cstdlib>
class IntSet {
public:
IntSet() {}
IntSet(int i);
IntSet(std::vector<int>& v);
void add(int el);
void remove(int el);
bool isMember(int el) const;
size_t size() const;
void display() const;
void clear();
int getMax() const;
int getMin() const;
private:
std::vector<int> set;
};
inline IntSet::IntSet(int i) {
set.push_back(i);
}
inline bool IntSet::isMember(int el) const {
for (size_t i = 0; i < set.size(); ++i) {
if (set.at(i) == el) return true;
return false;
}
}
inline size_t IntSet::size() const {
return set.size();
}
inline void IntSet::clear() {
set.clear();
}
inline int IntSet::getMax() const {
if (set.size() == 0) return 0;
else return set.at(set.size()-1);
}
inline int IntSet::getMin() const {
if (set.size() == 0) return 0;
else return set.at(0);
}
#endif
IntSet.cpp
Code:
#include "IntSet.h"
#include <algorithm>
#include <iostream>
IntSet::IntSet(std::vector<int>& v) {
std::sort(v.begin(), v.end());
for (size_t i = 1; i < v.size(); ++i) {
if (!(v.at(i) == v.at(i-1))) set.push_back(v.at(i));
}
}
void IntSet::add(int el) {
for (size_t i = 0; i < set.size(); ++i) {
if (set.at(i) == el) return;
}
set.push_back(el);
std::sort(set.begin(), set.end());
}
void IntSet::remove(int el) {
for (size_t i = 0; i < set.size(); ++i) {
if (set.at(i) == el) {
set.erase(set.begin() + i);
}
}
}
void IntSet::display() const {
if (set.size() == 0) {
std::cout << "\n( )";
} else {
std::cout << "\n(";
for (size_t i = 0; i < set.size(); ++i) {
std::cout << set.at(i);
if ((set.size() > 1) && (i < set.size()-1)) {
std::cout << ", ";
}
}
std::cout << ")";
}
}
I performed some test operations and the class seems to work as expected. Still I would appreciated any remarks.