c++

transform(a.begin(), a.end(), b.begin(), Lambda) 把 a 中的元素改为 b 中的元素经过 Lambda 后的元素。

内建函数

builtin 是内建的意思。下面函数的时间复杂度都是 \(O(1)\) 的。

__builtin_ctz(x) 返回末尾的 0 的个数(__builtin_ctz(0) 未定义)。这个函数在 Binary Gcd 中用到。

__builtin_popcount(x) 返回二进制下的 popcount。

Lambda

简单函数

[] 中,[=] 捕获外面所有的值,[&] 捕获外面所有的变量(可在函数内修改),[x] 捕获特定的值,[&x] 捕获特定的变量。

auto 返回的是类型是编译器推导出来的。

注意最后面要加个 ;,因为这本质是一种定义操作。

auto add = [&](int a, int b){
	return a + b;
};

auto greet = [&](const std::string& name, int age){
	std::cout << "Hello " << name << ", you are " << age << " years old." << std::endl;
};

auto sayHello = [&]{
	std::cout << "Hello!" << std::endl;
};

不敢 auto 的话,可以这样定义返回值类型:

auto explicitReturn = [&](double a, double b) -> double {
	if (b == 0) return 0; // 需要显式返回类型来统一返回类型
	return a / b;
};

递归函数

function<void(int)> dfs = [&](int x) 等价于 void dfs(int x)

function<void(int&)> dfs = [&](int &x) 等价于 void dfs(int &x)

function<void(int, int)> dfs = [&](int x, int y) 等价于 void dfs(int x, int y)

function<void(int, string)> dfs = [&](int x, string y) 等价于 void dfs(int x, string y)

function<void(int&, int)> dfs = [&](int &x, int y) 等价于 void dfs(int &x, int y)

function<void(int&, int&)> dfs = [&](int &x, int &y) 等价于 void dfs(int &x, int &y)

function<int(int&, int&)> dfs = [&](int &x, int &y) 等价于 int dfs(int x)

posted @ 2025-09-25 16:17  hhhqx  阅读(7)  评论(0)    收藏  举报