c++ 模板的一些

<p><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">stl中大量的运用了模板;</span></p>

今天就拿stl 的容器和一些相关的操作来说明下;


std::set

1、 添加自定义比较操作

template<class T>
struct LessCmp 
{
	bool operator() (const T lhs, const T rhs) const
	{
		return lhs < rhs;
	}
};

std::set<int, LessCmp<int>> ms;

2、循环遍历, 这个肯定木有难度了

template <class T>
void MyPrint(const T& lhs)
{
	std::cout << lhs << " ";
}
for_each(ms.begin(), ms.end(), MyPrint<int>);


3、遍历比较

一、 直接扔一个固定的数 在函数中比较,这个就不写了


二、直接来函数吧

template<class T, const int val>
bool FunCmp(const T& lhs) 
{
	MyPrint<int>(lhs);
	return lhs < val;
}
for_each(ms.begin(), ms.end(), FunCmp<int, 5>);


三、for_each(ms.begin(), ms.end(), std::bind2nd(std::greater<int>(),  5);, ///< bind1st  同理

四、仿造二自己实现一个

template <class T>
struct MyCmp : public std::binary_function < T, T, bool >
{
	bool operator() (const T& lhs, const T& rhs) const 
	{
		MyPrint<int>(lhs);

		return lhs < rhs;
	}
};

for_each(ms.begin(), ms.end(), std::bind2nd(MyCmp<int>(), 5));


五、来个麻烦的

template<class T, class P>
struct NewCompare 
{
	NewCompare(const P& p) : m_p(p) {}

	bool operator() (const T& lhs) const
	{
		return lhs < m_p;
	}

	P m_p;
};

for_each(ms.begin(), ms.end(), NewCompare<int, int>(5));

六、比四来说好些的

template<class T, int val>
struct NewCompare2
{
	bool operator() (const T& lhs) const
	{
		return lhs < val;
	}
};

for_each(ms.begin(), ms.end(), NewCompare2<int, 5>());







六、直接来函数吧

template<class T, const int val>
bool FunCmp(const T& lhs) 
{
	MyPrint<int>(lhs);
	return lhs < val;
}
for_each(ms.begin(), ms.end(), FunCmp<int, 5>);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值