前言
我们在日常生活中需给电脑充电,电脑时无法直接承受强大的电压,所以我们需要使用一个适配器来对电压进行转换,让我们的电脑能够通过适配器来充电。
在C++ STL中,我们想使用一个已经规定好的模板,但是这个模板需要做一些转换才能供我们使用,这便有了适配器的出现。
下面主要讲
- 函数适配器 bind1nd、bind2nd
- 容器适配器 stack、queue、priority_queue
一.函数适配器 bind1nd、bind2nd
如果想使用某一个函数,但是这个函数又并不完全符合我们使用的要求,那么我们就需要使用函数适配器bind1st, bind2nd,用来返回我们想要使用的函数
另外 bind的用法过多,参考另外一篇文章:bind函数适配器、利用bind回调实现无继承多态、men_fn将成员函数转换为函数对象
struct pred:public binary_function<int, int, bool>{
bool operator()(const int& lhs, const int& rhs)const{
if (lhs >= rhs){
cout << lhs << endl;
return true;
}
return false;
}
};
//例如,当vector中元素>=5时,将其打印出来
void test1(){
vector<int> vec{1,3,5,6,7,8};
for_each(vec.begin(), vec.end(), bind2nd(pred(), 5));
}
//例如,删除vector中>=5的元素
void test2(){
vector<int> vec{1,3,5,6,7,8};
vec.erase(remove_if(vec.begin(), vec.end(), bind2nd(std::greater_equal<int>(), 5)), vec.end());
for (auto& e : vec)
cout << e << endl;
}
二.容器适配器
stack、queue、priority_queue均为容器适配器
stack 与 queue 的标准模板为deque, stack与queue相当于只是实现的deque的一部分功能,不用再重新写函数了, 所以也就被成为容器适配器
priority_queue 的标准模板为vector,但是优先队列的逻辑实现是和最大堆,最小堆一致,底层仍然是用的二叉堆来实现
class Point{
public:
Point(int x, int y)
:_x(x)
,_y(y)
{
_sum = x + y;
}
int _x;
int _y;
int _sum;
friend ostream& operator<<(ostream& os, const Point& lhs);
};
ostream& operator<<(ostream& os, const Point& lhs){
os << lhs._sum;
return os;
}
struct myCompare{
bool operator()(const Point& lhs, const Point& rhs){
return lhs._sum > rhs._sum;
}
};
void test3(){
priority_queue<Point, vector<Point>, myCompare> myque;
myque.push(Point(1,1));
myque.push(Point(2,2));
myque.push(Point(3,3));
while (!myque.empty()){
cout << "Now the highest priority is :" << myque.top() << endl;
myque.pop();
}
}
int main(){
test3();
return 0;
}