1.transform 用法
static int op_increase(int i) { return ++i; }
void Solve() {
vector<int>arr(3);
for (auto& i : arr)cin >> i;
for (auto i : arr)cout << i << " ";
cout << endl;
transform(arr.begin(), arr.end(), arr.begin(), [](int a) {
return a * 10;
});
for (auto i : arr)cout << i << " ";
cout << endl;
transform(arr.begin(), arr.end(), arr.begin(),
[](int a)->int {return a * 10; });
for (auto i : arr)cout << i << " ";
cout << endl;
for_each(arr.begin(), arr.end(), [](int &a) {a *= 10; });
for (auto i : arr)cout << i << " ";
cout << endl;
vector<int> b;
b.resize(arr.size());
transform(arr.begin(), arr.end(), b.begin(),
op_increase);//对a中每个值经过op_increase给b
transform(arr.begin(), arr.end(), b.begin(),
[](int a)->int {return a + 10; });//对a中每个值经过op_increase给b
transform(arr.begin(), arr.end(),b.begin(), arr.begin(), std::plus<int>());
//plus 累加
int sum = accumulate(arr.begin(), arr.end(), 0, plus<int>());
//accumlate可以缺省plus<int>(),默认的
cout << sum << endl;
for (auto i : arr)cout << i << " ";
cout << endl;
for (auto i : b)cout << i << " ";
cout << endl;
}
2.C++ lambda表达式
C++11中Lambda表达式的使用
3.remove:
remove_if用法
static int op_increase(int i) { return ++i; }
void Solve() {
vector<int>arr(3);
for (auto& i : arr)cin >> i;
transform(arr.begin(), arr.end(), arr.begin(), [](int a) {
return a * 10;
});
for (auto i : arr)cout << i << " ";
cout << endl;
int k = 40;
//remove(arr.begin(),arr.end(),val)将=val放在最后,没有删除,需要erase
arr.erase(remove_if(arr.begin(), arr.end(), [k](int n) {return n > k; }),arr.end());
for (auto i : arr)cout << i << " ";
}
4.函数表达形式:
int add(int a, int b){
return a+b;
}
auto mod=[](int a, int b){return a%b;};
struct divide{
int operator()(int m, int n){
return m/n;
}
};
auto func1 = [](int i) { return i + 4; };
std::cout << "func1: " << func1(6) << '\n';
function<int(int)> fun1 = func1;//调用形式
auto mod = [](int a, int b) {return a % b; };
struct divide {
int operator()(int m, int n) {
return m / n;
}
};
//抽象定义,不同类型采用相同的调用方法:
map<string, function<int(int, int)>> funs =
{
{"+", add},
{"-", std::minus<int>()},//标准库的函数,参数为两个整数,可以参考前一篇博客
{"/", divide()},//类成员函数
{"*", [](int i,int j) {return i * j; }},//lambda表达式
{"%", mod},
};
funs["+"](4, 6);
funs["*"](4 , 2);
5.对于set的自定义函数重载
int k;
struct cmp {
bool operator()(const int& u, const int& v) const{
if (abs(u - v) <= k)return false;//false 不需要插入进去,insert失效
return u < v;
}
};
set<int, cmp>se;