目录
- 一、容器适配器
- 二、仿函数
一、容器适配器
容器适配器其实是一种设计模式。转换出我们想要的东西。
比方说我们实现栈的时候既可以用数组,也可以用链表,此时我们就可以用到容器适配器了。
namespace yyh
{
template <class T, class container = vector<T>>
class stack
{
public:
void push(const T& x)
{
_con.push_back(x);
}
void pop()
{
_con.pop_back();
}
const T& top()
{
return _con.back();
}
bool empty()
{
return _con.empty();
}
private:
container _con;
};
}
int main()
{
yyh::stack<int, vector<int>> st1;
yyh::stack<int, list<int>> st2;
return 0;
}
这样我们就可以用不同的底层实现栈了。
二、仿函数
仿函数其实就是用类重载()的方式来模拟一个函数。
我们现在写一个比较大小的仿函数
namespace yyh
{
template <class T>
struct less
{
bool operator()(const T& x, const T& y)
{
return x < y;
}
};
template <class T>
struct greater
{
bool operator()(const T& x, const T& y)
{
return x > y;
}
};
}
这个类我们就可以成为仿函数,而该类的对象成为函数对象。
用法:
当我们想同时派升序和降序的时候,我们可以利用仿函数来进行比较。
namespace yyh
{
template <class T>
struct less
{
bool operator()(const T& x, const T& y)
{
return x < y;
}
};
template <class T>
struct greater
{
bool operator()(const T& x, const T& y)
{
return x > y;
}
};
template <class T, class compare>
void BubbleSort(vector<T>& a, compare com)
{
for (int i = 0; i < a.size() - 1; i++)
{
//用来判断是否交换过,提高效率
int flag = 1;
for (int cur = 0; cur < a.size() - 1 - i; cur++)
{
if (com(a[cur + 1], a[cur]))
{
swap(a[cur], a[cur + 1]);
flag = 0;
}
}
if (flag)
{
break;
}
}
}
}
int main()
{
yyh::less<int> lessFun;
vector<int> v1;
v1.push_back(1);
v1.push_back(5);
v1.push_back(2);
v1.push_back(4);
v1.push_back(3);
yyh::BubbleSort(v1, lessFun);
for (auto e : v1)
{
cout << e << " ";
}
return 0;
}

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)