title: c++functional
categories: 编程
tags:
- c++
date: 2022-04-06 15:26:27
functional谓词标准
#include
主要是配合algorithm的谓词需要,减少代码量。多为二元谓词。
代码示例
准备工作
#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>
using namespace std;
void PrintV(int v)
{
cout << v << " ";
}
bool large(int a)
{
if (a > 5)
{
return true;
}
else
{
return false;
}
}
void show(vector<int> v)
{
for_each(v.begin(), v.end(), PrintV);
cout << endl;
}
主函数
int main()
{
vector<int> v;//示例容器
vector<int> new_v;//复制容器
vector<int> reunion;//合并容器
reunion.resize(30);
vector<int>::iterator it;//返回迭代器
new_v.resize(10);
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//transform操作后放入新区域
transform(v.begin(), v.end(), new_v.begin(), negate<int>());
show(new_v);//取负数
//sort
sort(v.begin(), v.end(),greater<int>());//greater大于排序
show(v);//比较运算一般用于sort排序
//merge
merge(v.begin(), v.end(), new_v.begin(), new_v.end(),reunion.begin(),less<int>());
show(reunion);//小于
cout << "---------------" << endl;
cout << "end" << endl;
return 0;
}
运行结果
0 -1 -2 -3 -4 -5 -6 -7 -8 -9
9 8 7 6 5 4 3 2 1 0
0 -1 -2 -3 -4 -5 -6 -7 -8 -9 9 8 7 6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0
---------------
end