通用的set容器

通用的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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值