<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>);
一、 直接扔一个固定的数 在函数中比较,这个就不写了
二、直接来函数吧
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>);