求問這道題怎么做
設計一個集合類模板,完成集合的并交差運算
已給主函式和運行結果(要用多載)
uj5u.com熱心網友回復:
直接用vector, 外部定義下template<class T_>
std::vector<T_> operator+(const std::vector<T_>& a, const std::vector<T_>& b);
template<class T_>
std::vector<T_> operator*(const std::vector<T_>& a, const std::vector<T_>& b);
template<class T_>
std::vector<T_> operator-(const std::vector<T_>& a, const std::vector<T_>& b);
uj5u.com熱心網友回復:
vector好像沒學過
uj5u.com熱心網友回復:
template<class T_>
class Set {
T_* m_v =0;
int m_n =0;
public:
Set() {};
Set(int n_) { m_n = n_; m_v = m_n ? new T_[m_n] :0; };
template<int n_>
Set(T_ (&v_)[n_]) :Set(n_){
for (int i = 0; i < m_n; i++)
m_v[i] = v_[i];
};
~Set() { delete[]m_v; };
public:
const T_* begin() const { return m_v; }
const T_* end() const { return m_v + m_n; }
T_* begin() { return m_v; }
T_* end() { return m_v + m_n; }
int size() const { return m_n; }
const T_& operator[](int n) const { assert(n < m_n); return m_v[n]; };
T_& operator[](int n) { assert(n < m_n); return m_v[n]; };
void show() const{
for (auto& i : *this)
std::cout << i << " ";
std::cout << std::endl;
}
Set (const Set<T_>& a) {
this->m_n = a.size();
this->m_v = new T_[this->m_n];
for (int i = 0; i < m_n; i++)
m_v[i] = a[i];
}
Set<T_>& operator=(const Set<T_>& a) {
delete[]this->m_v;
this->m_n = a.size();
this->m_v = new T_[this->m_n];
for (int i = 0; i < m_n; i++)
m_v[i] = a[i];
return *this;
}
Set<T_> operator-(const Set<T_>& b) const{
//
int nn = 0;
for (auto& i : (*this))
{
for (auto& j : b)
if (i == j) {
nn++;
break;
}
}
nn = this->m_n - nn;
//
Set<T_> r(nn);
if (nn)
{
nn = 0;
for (auto& i : (*this))
{
bool fnd = 0;
for (auto& j : b)
if (i == j) {
fnd =true;
break;
}
if (!fnd)
r[nn++] = i;
}
}
return r;
}
Set<T_> operator+(const Set<T_>& b) const {
Set<T_> u = (*this) - b;
Set<T_> v = b - (*this);
Set<T_> r(u.size() + v.size());
int n = 0;
for (auto& i : u)
r[n++] = i;
for (auto& i : v)
r[n++] = i;
return r;
}
Set<T_> operator*(const Set<T_>& b) const {
return (*this) - ((*this) - b);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/87366.html
標籤:C++ 語言
下一篇:proc中fetch的問題
