C++14中lambda表达式新增加的features的使用

2023-05-16

      lambda表达式是在C++11中引入的,它们可以嵌套在其它函数甚至函数调用语句中,C++11中lambda表达式的使用参考:https://blog.csdn.net/fengbingchun/article/details/52653313

      lambda表达式语法如下:除capture和body是必须的,其它均是可选的

[capture] (params) mutable exception attribute -> return-type { body }

      这里介绍下C++14中对lambda表达式新增加的features:

      1.generic lambda:lambda表达式与auto关键字组合,将auto用作参数类型,以下为测试代码:

namespace {

//void print_elements(auto& C) // windows need to c++20
template<typename T>
void print_elements(const T& C)
{
	for (const auto& e : C)
		std::cout << e << " ";
	std::cout << "\n";
}

}

int test_lambda_14_1()
{
	// reference: https://www.geeksforgeeks.org/generalized-lambda-expressions-c14/
	/* Under the hood, the C++ implementation uses the closure type’s operator() to overload a template function
	struct sum {
		template<typename T1, typename T2>
		auto operator()(T1 a, T2 b) const { return (a + b); }
	};
	*/
	auto sum = [](auto a, auto b) {
		return (a + b);
	};

	std::cout << "int sum:" << sum(10, 20) << "\n";
	std::cout << "float sum:" << sum(1.2f, 2.3f) << "\n";
	std::cout << "float sum:" << sum(10, 1.5f) << "\n";
	std::cout << "string sum:" << sum(std::string("csdn addr:"), std::string("https://blog.csdn.net/fengbingchun")) << "\n";


	auto greater = [](auto a, auto b) -> bool {
		return (a > b);
	};

	std::vector<int> vi = { 1, 4, 2, 6 };
	std::vector<float> vf = { 4.62f, 161.3f, 62.26f, 13.4f };
	std::vector<std::string> vs = { "Tom", "Harry", "Ram", "Shyam" };

	std::sort(vi.begin(), vi.end(), greater);
	std::sort(vf.begin(), vf.end(), greater);
	std::sort(vs.begin(), vs.end(), greater);

	print_elements(vi);
	print_elements(vf);
	print_elements(vs);


	std::vector<std::vector<int>> v = { {7, 8}, {1, 2}, {3, 7}, {4, 5} };
	std::sort(v.begin(), v.end(), [](std::vector<int>& a, std::vector<int>& b) {
		return (a[1] < b[1]);
	});

	for (int i = 0; i < v.size(); ++i) {
		for (int j = 0; j < v[0].size(); ++j) {
			std::cout << v[i][j] << " ";
		}
		std::cout << "\n";
	}

	return 0;
}

      执行结果如下图所示:

      2.capture initializers:允许创建使用任意表达式初始化captures初始化表达式在创建lambda时计算,而不是在调用时,以下为测试代码:

namespace { int factory(int i) { return i * 10; } }

int test_lambda_14_2()
{
	// reference: https://github.com/AnthonyCalandra/modern-cpp-features#lambda-capture-initializers
	auto f = [x = factory(2)] { return x; };
	std::cout << "f:" << f() << "\n";


	auto generator = [x = 0]() mutable {
		// this would not compile without 'mutable' as we are modifying x on each call
		return x++;
	};

	auto a = generator();
	auto b = generator();
	auto c = generator();
	std::cout << "a:" << a << ",b:" << b << ",c:" << c << "\n";


	auto p = std::make_unique<int>(1);
	//auto task1 = [=] { *p = 5; }; // ERROR: std::unique_ptr cannot be copied
	auto task2 = [p = std::move(p)] { *p = 5; return *p; }; // OK: p is move-constructed into the closure object
	// the original p is empty after task2 is created
	if (!p)
		std::cout << "p is empty" << "\n";
	std::cout << "task2:" << task2() << "\n";


	auto x = 2;
	auto f2 = [&r = x, x = x * 10] {
		++r;
		return r + x;
	};
	std::cout << "f2:" << f2() << ",x:" << x << "\n";

	return 0;
}

      执行结果如下图所示:

      GitHub:https://github.com/fengbingchun/Messy_Test

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++14中lambda表达式新增加的features的使用 的相关文章

随机推荐

  • JWT(JSON Web Token)简介及实现

    JWT JSON Web Token xff1a 是一个开放标准 RFC 7519 xff0c 它定义了一种紧凑且自包含的方式 xff0c 用于在各方之间作为Json对象安全地传输信息 由于此信息是经过数字签名的 xff0c 因此可以被验证
  • SSL/TLS单向认证和双向认证介绍

    为了便于理解SSL TLS的单向认证和双向认证执行流程 xff0c 这里先介绍一些术语 1 散列函数 Hash function xff1a 又称散列算法 哈希函数 xff0c 是一种从任何一种数据中创建小的数字 指纹 的方法 散列函数把消
  • 使用OpenSSL生成自签名证书相关命令

    在用于小范围测试等目的的时候 xff0c 用户也可以自己生成数字证书 xff0c 但没有任何可信赖的机构签名 xff0c 此类数字证书称为自签名证书 证书一般采用X 509标准格式 下面通过OpenSSL相关命令介绍如何生成自签证书 1 生
  • Windows/Linux TCP Socket网络编程简介及测试代码

    典型的网络应用是由一对程序 即客户程序和服务器程序 组成的 xff0c 它们位于两个不同的端系统中 当运行这两个程序时 xff0c 创建了一个客户进程和一个服务器进程 xff0c 同时它们通过从套接字 socket 读出和写入数据在彼此之间
  • 基于BearSSL实现自签名证书双向认证测试代码

    客户端 服务器端双向认证大致过程 xff1a 可以参考 xff1a https blog csdn net fengbingchun article details 106856332 1 客户端发起连接请求 xff1b 2 服务器端返回消
  • C:\KEIL\C51\intrins.h包含不正确的路径。Keil 头文件路径错误

    步骤1 xff1a 先检查工程中的 include intrins h include stdio h xff0c 各文件之间 是否正确调用 步骤2 xff1a 将 include lt intrins h gt lt reg52 h gt
  • 分享一个Centos8的国内yum源

    使用的是阿里巴巴开源镜像站 xff0c 文件地址 xff1a https span class token punctuation span span class token operator span span class token o
  • 网络数据包分析软件Wireshark简介

    Wireshark是被广泛使用的免费开源的网络协议分析软件 network protocol analyzer 或网络数据包分析软件 xff0c 它可以让你在微观层面上查看网络上发生的事情 xff0c 它的功能是截取网络数据包 xff0c
  • HTTP请求方法介绍

    之前在https blog csdn net fengbingchun article details 85039308 中介绍过HTTP协议 xff0c 在https blog csdn net fengbingchun article
  • TCP Flags标志位介绍

    传输控制协议 Transmission Control Protocol xff0c TCP 是一种传输层协议 TCP使数据包从源到目的地的传输更加顺畅 它是一种面向连接的端到端协议 每个数据包由TCP包裹在一个报头中 xff0c 该报头由
  • 代理服务器简介及libcurl测试

    代理服务器英文全称是Proxy Server xff0c 其功能就是将局域网用户连接到Internet xff0c 代理网络用户去获得网络信息 形象地说 xff0c 它是网络信息的中转站 xff0c 是连接内部局域网和Internet的一种
  • CMake中find_package的使用

    CMake中的命令find package用于查找指定的package find package支持两种主要的搜索方法 xff1a 注意 xff1a lt PackageName gt 是区分大小写的 1 Config mode 配置模式
  • CMake中link_directories/target_link_directories的使用

    CMake中的link directories命令用于添加目录使链接器能在其查找库 add directories in which the linker will look for libraries xff0c 其格式如下 xff1a
  • UDP协议在Windows上使用示例

    UDP User Datagram Protocol xff0c 用户数据报协议 是无连接的 xff0c 因此在两个进程通信前没有握手过程 UDP协议提供一种不可靠数据传送服务 xff0c 也就是说 xff0c 当进程将一个报文发送进UDP
  • 代码覆盖率工具OpenCppCoverage在Windows上的使用

    OpenCppCoverage是用在Windows C 43 43 上的开源的代码覆盖率工具 xff0c 源码地址为https github com OpenCppCoverage OpenCppCoverage xff0c 最新发布版本为
  • nerfstudio介绍及在windows上的配置、使用

    nerfstudio提供了一个简单的API xff0c 可以简化创建 训练和可视化NeRF的端到端过程 该库通过模块化每个组件来支持可解释的NeRF实现 nerfstudio源码地址 https github com nerfstudio
  • Qt中QDebug的使用

    QDebug类为调试信息 debugging information 提供输出流 它的声明在 lt QDebug gt 中 xff0c 实现在Core模块中 将调试或跟踪信息 debugging or tracing information
  • OkHttpUtil

    package com example someutil util import com google gson Gson import java util Iterator import java util Map import java
  • Sourcetree介绍及使用

    Sourcetree是一个操作简单但功能强大的免费Git客户端管理工具 xff0c 可应用在Windows和Mac平台 Sourcetree的安装 xff1a 1 从Sourcetree Free Git GUI for Mac and W
  • C++14中lambda表达式新增加的features的使用

    lambda表达式是在C 43 43 11中引入的 xff0c 它们可以嵌套在其它函数甚至函数调用语句中 xff0c C 43 43 11中lambda表达式的使用参考 xff1a https blog csdn net fengbingc