改为继承实现。
This commit is contained in:
@@ -53,13 +53,19 @@ int main() {
|
||||
cout << "\n----------\n" << endl;
|
||||
|
||||
Set<int> aSet;
|
||||
aSet.show();
|
||||
output(aSet);
|
||||
|
||||
aSet.add(2);
|
||||
aSet.add(3);
|
||||
aSet.show();
|
||||
aSet.append(2);
|
||||
aSet.append(3);
|
||||
output(aSet);
|
||||
try {
|
||||
aSet.append(2);
|
||||
}
|
||||
catch(DuplicateError) {
|
||||
cout << "Duplicate Element!" << endl;
|
||||
}
|
||||
|
||||
aSet.remove(2);
|
||||
aSet.show();
|
||||
output(aSet);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,69 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "ListExceptions.h"
|
||||
#include "listE.h"
|
||||
|
||||
template <class E> class Set {
|
||||
private:
|
||||
List<E> _list;
|
||||
|
||||
template <class E> class Set : public List<E> {
|
||||
public:
|
||||
Set();
|
||||
Set(const E &_newItem);
|
||||
Set(const E *_newItem, const int count);
|
||||
// Add an element.
|
||||
Set<E> &add(const E &_newItem);
|
||||
// Remove an element.
|
||||
Set<E> &remove(const E &target);
|
||||
// Clear all elements.
|
||||
Set<E> &clear();
|
||||
|
||||
int size();
|
||||
void show();
|
||||
};
|
||||
|
||||
template <class E> Set<E>::Set() : _list(){};
|
||||
|
||||
template <class E> Set<E>::Set(const E &_newItem) : _list(_newItem){};
|
||||
|
||||
template <class E> Set<E>::Set(const E *_newItem, const int count) : _list() {
|
||||
for (int i = 0; i < count; i++) {
|
||||
try {
|
||||
this->add(_newItem[i]);
|
||||
}
|
||||
catch (DuplicateError) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <class E> Set<E> &Set<E>::add(const E &_newItem) {
|
||||
if (_list.contains(_newItem)) {
|
||||
List<E> &append(const E &_newItem) {
|
||||
if (this->contains(_newItem)) {
|
||||
throw(DuplicateError());
|
||||
}
|
||||
|
||||
_list.append(_newItem);
|
||||
List<E>::append(_newItem);
|
||||
return *this;
|
||||
}
|
||||
|
||||
List<E> &insert(int index, const E &_newItem) = delete;
|
||||
|
||||
E pop(int index) = delete;
|
||||
|
||||
int index(const E &target) = delete;
|
||||
};
|
||||
|
||||
template <class E> Set<E> &Set<E>::remove(const E &target) {
|
||||
_list.remove(target);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <class E> Set<E> &Set<E>::clear() {
|
||||
_list.clear();
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <class E> int Set<E>::size() {
|
||||
return _list.length();
|
||||
}
|
||||
|
||||
template <class E> void Set<E>::show() {
|
||||
for (int i = 0; i < _list.length(); i++) {
|
||||
std::cout << _list[i] << ' ';
|
||||
}
|
||||
if (_list.length() == 0) {
|
||||
std::cout << "(Empty)";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
Reference in New Issue
Block a user