std::bind1st和std::bind2nd
头文件:fuctional
std::bind1st和std::bind2nd函数用于将一个二元算子转换成一元算子。
bind的意思是“绑定”,1st代表first,2nd代表second,它们的声明如下:
//std::bind1st
template <class Operation, class T>
binder1st<Operation> bind1st (const Operation& op, const T& x);
//std::bind2nd
template <class Operation, class T>
binder2nd<Operation> bind2nd (const Operation& op, const T& x);
bind1st相当于作这样的操作:x op value;
bind2nd相当于作这样的操作:value op x;
演示程序:
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
const int Len = 10;
int main()
{
int num[Len] = { 1, 2, 30, 50, 100, 200, 300, 400, 217, 120 };
std::vector<int> arr(num, num + Len);
//移除所有小于100的元素, 相当于arr.value < 100
arr.erase(std::remove_if(arr.begin(), arr.end(),
std::bind2nd(std::less<int>(), 100)), arr.end());
for (auto elem : arr)
{
std::cout << elem << " "; //input: 100 200 300 400 217 120
}
std::cout << std::endl;
//移除所有大于300的元素, 相当于300 < arr.value
arr.erase(std::remove_if(arr.begin(), arr.end(),
std::bind1st(std::less<int>(), 300)), arr.end());
for (auto elem : arr)
{
std::cout << elem << " "; //input: 100 200 300 217 120
}
std::cout << std::endl;
//移除所有大于200的元素, 相当于arr.value > 200
arr.erase(std::remove_if(arr.begin(), arr.end(),
std::bind2nd(std::greater<int>(), 100)), arr.end());
for (auto elem : arr)
{
std::cout << elem << " "; //input: 100
}
std::cout << std::endl;
//移除所有小于等于100的元素, !(x > k) == (x <= k)
arr.erase(std::remove_if(arr.begin(), arr.end(),
std::not1(std::bind2nd(std::greater<int>(), 100))), arr.end());
for (auto elem : arr)
{
std::cout << elem << std::endl; //input:
}
return 0;
}
not1是否定返回值单目的函数,还有一个not2是否定返回值是双目的函数。
分类:
[002] C/C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2014-08-29 关于typedef的用法总结(zz)