通用的set容器
sizeFilter.hpp
#pragma once
/*
实现一个通用容器,支持插入不同类型数据,和自定义结构体\自定义类对象
并从容器中数据进行比较取最大值和最小值
*/
#include<set>
#include<iostream>
template<class _Ty,class _Container=std::set<_Ty>>
class sizeFilter
{
public:
typedef sizeFilter<_Ty, _Container> _Myt;
typedef typename _Container::size_type size_type;
typedef typename _Container::value_type value_type;
sizeFilter() {
//默认构造函数,初始化内置容器
};
sizeFilter(const _Myt& _Rigth) {
//构造函数,通过指定特定的sizeFilter容器构造
};
sizeFilter(const _Container& _Cont) {
//构造函数,通过指定的容器构造
};
//使用另一个sizeFilter赋值,可以A=B=C=D
_Myt& operator=(const _Myt& _Rigth) {
c = _Rigth.c;
return (*this);
};
//测试sizeFilter的长度
size_type size()const {
return (c.size());
};
//判断sizeFilter是否为空
bool empty() const {
return (c.empty());
};
//插入元素
bool insert(const value_type& _Val) {
typename _Container::iterator ci = c.insert(c.begin(), _Val);
if(ci != c.end()) {
std::cout << "插入" << _Val << "成功" << std::endl;
return true;
}
};
//擦除元素
bool erase(const value_type& _Val) {
if (c.erase(_Val) > 0) {
return true;
}
return false;
};
//获取最小值
std::pair < value_type, bool>getMin() {
std::pair<value_type, bool> ret;
typename _Container::iterator min = c.begin();
if (min != c.end()) {
ret.first = *min;
ret.second = true;
return ret;
}
ret.second = false;
return ret;
};
//获取最大值
std::pair<value_type, bool>geyMax() {
std::pair<value_type, bool> ret;
typename _Container::iterator end = c.end();
if (c.size() > 0) {
ret.first = *(--end);
ret.second = true;
}
else {
ret.second = false;
}
return ret;
};
protected:
_Container c;
};
main.cpp:
#include<iostream>
#include"sizeFilter.hpp"
#include<set>
using namespace std;
int main() {
sizeFilter<int, set<int>>sf;
for (int i = 0; i < 10; i++) {
sf.insert(i * 10);
}
sf.erase(90);
sf.erase(0);
pair<int, bool>pb = sf.geyMax();
if (pb.second) {
cout << "Max:" << pb.first << endl;
}
else {
cout << "没有最大值" << endl;
}
pair<int, bool> bx = sf.getMin();
if (bx.second) {
cout << "最小值为:" << bx.first << endl;
}
}