C++现代教程五

news2024/9/23 13:16:09
#pragma once
_Pragma("once")

# C/C++混合编程
#ifdef __cplusplus
extern "C" {
#endif
// 一些c代码
#ifdef __cplusplus
}
#endif

# 继承构造
struct A
{
  A(int i) {}
  A(double d,int i){}
  A(float f,int i,const char* c){}
  //...等等系列的构造函数版本
};
old:
struct B:A
{
  B(int i):A(i){}
  B(double d,int i):A(d,i){}
  B(folat f,int i,const char* c):A(f,i,e){}
  //......等等好多个和基类构造函数对应的构造函数
};
new:
struct B:A
{
  using A::A;
  //关于基类各构造函数的继承一句话搞定
  //......
};

#regex
std::regex base_regex("([a-z]+)\\.txt");
std::smatch base_match;
for(const auto &fname: fnames) {
    if (std::regex_match(fname, base_match, base_regex)) {
        // sub_match 的第一个元素匹配整个字符串
        // sub_match 的第二个元素匹配了第一个括号表达式
        if (base_match.size() == 2) {
            std::string base = base_match[1].str();
            std::cout << "sub-match[0]: " << base_match[0].str() << std::endl;
            std::cout << fname << " sub-match[1]: " << base << std::endl;
        }
    }
}

#Variadic templates

// C++11
template <typename First, typename... Args>
auto sum(const First first, const Args... args) -> decltype(first) {
  const auto values = {first, args...};
  return std::accumulate(values.begin(), values.end(), First{0});
}

// C++17
template <typename... Args>
auto sum(Args... args) {
    // Unary folding.
    return (... + args);
}

template <typename... Args>
bool logicalAnd(Args... args) {
    // Binary folding.
    return (true && ... && args);
}
bool b = true;
bool& b2 = b;
logicalAnd(b, b2, true); // == true

#Inline namespaces
namespace Program {
  namespace Version1 {
    int getVersion() { return 1; }
    bool isFirstVersion() { return true; }
  }
  inline namespace Version2 {
    int getVersion() { return 2; }
  }
}

int version {Program::getVersion()};              // Uses getVersion() from Version2
int oldVersion {Program::Version1::getVersion()}; // Uses getVersion() from Version1
bool firstVersion {Program::isFirstVersion()};    // Does not compile when Version2 is added

# std::move temp
struct Bar {
    int a = 1;
};

struct Foo {
    Bar getBar() & { return bar; }
    Bar getBar() const& { return Bar{}; }
    Bar getBar() && { return std::move(Bar{}); }
private:
    Bar bar;
};

Foo foo;
auto&& ref = foo.getBar();
ref.a = 10;

# Nested namespaces
namespace A::B::C {
  int i;
}

# __has_include
#ifdef __has_include
#  if __has_include(<optional>)
#    include <optional>
#    define have_optional 1
#  elif __has_include(<experimental/optional>)
#    include <experimental/optional>
#    define have_optional 1
#    define experimental_optional
#  else
#    define have_optional 0
#  endif
#endif

# std::invoke
template <typename Callable>
class Proxy {
  Callable c_;

public:
  Proxy(Callable c) : c_{ std::move(c) } {}

  template <typename... Args>
  decltype(auto) operator()(Args&&... args) {
    // ...
    return std::invoke(c_, std::forward<Args>(args)...);
  }
};

const auto add = [](int x, int y) { return x + y; };
Proxy p{ add };
p(1, 2); // == 3

# std::clamp limitRange
std::clamp(0, -1, 1, std::less<>{}); // == 0

# std::reduce  
const std::array<int, 3> a{ 1, 2, 3 };
std::reduce(std::cbegin(a), std::cend(a)); // == 6  default binary operation is std::plus 
// Using a custom binary op:
std::reduce(std::cbegin(a), std::cend(a), 1, std::multiplies<>{}); // == 6

const std::array<int, 3> b{ 1, 2, 3 };
const auto product_times_ten = [](const auto a, const auto b) { return a * b * 10; };
std::transform_reduce(std::cbegin(a), std::cend(a), std::cbegin(b), 0, std::plus<>{}, product_times_ten); // == 140

# std::inclusive_scan
const std::array<int, 3> a{ 1, 2, 3 };

std::inclusive_scan(std::cbegin(a), std::cend(a),
    std::ostream_iterator<int>{ std::cout, " " }, std::plus<>{}); // 1 3 6

std::exclusive_scan(std::cbegin(a), std::cend(a),
    std::ostream_iterator<int>{ std::cout, " " }, 0, std::plus<>{}); // 0 1 3

const auto times_ten = [](const auto n) { return n * 10; };

std::transform_inclusive_scan(std::cbegin(a), std::cend(a),
    std::ostream_iterator<int>{ std::cout, " " }, std::plus<>{}, times_ten); // 10 30 60

std::transform_exclusive_scan(std::cbegin(a), std::cend(a),
    std::ostream_iterator<int>{ std::cout, " " }, 0, std::plus<>{}, times_ten); // 0 10 30
	
# GCD and LCM 公倍数
const int p = 9;
const int q = 3;
std::gcd(p, q); // == 3
std::lcm(p, q); // == 9

# std::not_fn

# C++20 Coroutines
generator<int> range(int start, int end) {
  while (start < end) {
    co_yield start;
    start++;
  }

  // Implicit co_return at the end of this function:
  // co_return;
}

for (int n : range(0, 10)) {
  std::cout << n << std::endl;
}

# concept
template <typename T>
concept unsigned_integral = integral<T> && !signed_integral<T>;

template <typename T>
concept callable = requires (T f) { f(); };

// `T` is a constrained type template parameter.
template <typename T>
  requires my_concept<T>
void f(T v);

# [[likely]] and [[unlikely]] attributes
switch (n) {
case 1:
  // ...
  break;

[[likely]] case 2:  // n == 2 is considered to be arbitrarily more
  // ...            // likely than any other value of n
  break;
}

int random = get_random_number_between_x_and_y(0, 3);
if (random > 0) [[likely]] {
  // body of if statement
  // ...
}

# constexpr virtual functions
struct X1 {
  virtual int f() const = 0;
};

struct X2: public X1 {
  constexpr virtual int f() const { return 2; }
};

# explicit(bool)
struct foo {
  // Specify non-integral types (strings, floats, etc.) require explicit construction.
  template <typename T>
  explicit(!std::is_integral_v<T>) foo(T) {}
};

# enum 
enum class rgba_color_channel { red, green, blue, alpha };

std::string_view to_string(rgba_color_channel my_channel) {
  switch (my_channel) {
    using enum rgba_color_channel;
    case red:   return "red";
    case green: return "green";
    case blue:  return "blue";
    case alpha: return "alpha";
  }
}

# constinit
const char* g() { return "dynamic initialization"; }
constexpr const char* f(bool p) { return p ? "constant initializer" : g(); }

constinit const char* c = f(true); // OK
constinit const char* d = f(false); // ERROR: `g` is not constexpr, so `d` cannot be evaluated at compile-time.

# std::span
std::span<const int, 3>{ c.cbegin(), c.cend() }

# Bit operations
std::popcount(0u); // 0
std::popcount(1u); // 1
std::popcount(0b1111'0000u); // 4

# Math constants
std::numbers::pi; // 3.14159...
std::numbers::e; // 2.71828..

# starts_with and ends_with on strings
std::string str = "foobar";
str.starts_with("foo"); // true
str.ends_with("baz"); // false

# std::midpoint
std::midpoint(1, 3); // == 2

# std::to_array
int a[] = {1, 2, 3};
std::to_array(a); // returns `std::array<int, 3>`

C++现代教程四_c++ float 转 string-CSDN博客


创作不易,小小的支持一下吧!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2041746.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

protobuf 生成 error

一、简介 响应错误时可以直接使用 errors 包中的 New 方法来声明一个 error&#xff0c;也可以直接通过 proto 预定义定义错误码&#xff0c;然后通过 proto-gen-go 生成帮助代码&#xff0c;直接返回 error。 二、使用教程 2.1 错误定义 syntax "proto3"; impor…

深入理解Java中的LocalDateTime与ChronoUnit:精确时间处理的最佳实践

个人名片 &#x1f393;作者简介&#xff1a;java领域优质创作者 &#x1f310;个人主页&#xff1a;码农阿豪 &#x1f4de;工作室&#xff1a;新空间代码工作室&#xff08;提供各种软件服务&#xff09; &#x1f48c;个人邮箱&#xff1a;[2435024119qq.com] &#x1f4f1…

人工智能战略:如何实施人工智能解决方案以实现企业成功

人工智能 (AI) 不再是一个未来概念&#xff0c;而是改变全球各行各业的切实现实。 企业正在利用人工智能来提高效率、提高生产力并获得竞争优势。然而&#xff0c;实施人工智能解决方案需要明确的战略。 本指南将引导您完成成功将人工智能融入业务运营的关键步骤&#xff0c;…

局部场电位LFP

声明&#xff1a;本文章是根据网上资料&#xff0c;加上自己整理和理解而成&#xff0c;仅为记录自己学习的点点滴滴。可能有错误&#xff0c;欢迎大家指正。 神经科学最伟大的发现之一是人脑的电活动可以用附在头皮上的电极进行无创测量。脑电图&#xff08;Electroencephalog…

四种实用办法恢复回收站清空的文件!

想要恢复回收站的文件不小心点成清空回收站&#xff0c;如果你也遇上同样的状况&#xff0c;想在回收站找回清空的文件&#xff0c;可以尝试以下这几个恢复办法。 方法一&#xff1a;借用云存储/存储设备找回丢失文件 如果丢失的文件在其他云存储软件上&#xff08;如百度网盘…

一款方便、高效的基于tree-sitter的代码风格转换器,支持Python、C/C++和Java共100多种风格转换

文章目录 工具介绍环境搭建使用教程工具框架流程图增删算法tree-sitter介绍项目目录结构说明风格列表 ​ 源代码网址&#xff1a;https://github.com/rebibabo/SCTS/tree/main 如果有引用本文或者工具&#xff0c;请注明引用来源 如果觉得对您有帮助&#xff0c;还请各位帅哥…

qt客户端与服务端关于传输文件

如果直接发 发送的数据永远要比接受的块 需要有时间间隔 此时定时器的作用就显现出来了 发送数据都先发头&#xff0c;要保证服务器发送的头&#xff0c;客户端能接受到 发送数据后不要直接读数据&#xff0c;加一个延迟 这里以##作为分隔符 发送多少读多少&#xff0c; 发送…

启程与远征Ⅲ--很棒的大语言模型代理

这是关于什么的&#xff1f; 这篇 Awesome-LLM-Agents 是对 Agentic AI 上的最新里程碑论文和开源项目的深度优先回顾。 这个 Awesome-LLM-Agents 项目是我在LLM-Agents-in-Production主题上建立专业知识的第一步&#xff0c;我打算将这个故事用作知识库&#xff0c;记录项目…

Unity转Unreal5从入门到精通之不同的Actor之间如何交互

前言 Unreal不同的Actor蓝图之间如何交互 当我们使用蓝图时&#xff0c;当碰到交互的时候&#xff0c;可能会有点蒙&#xff0c;平时我们写代码&#xff0c;A调用B的函数&#xff0c;非常简单。那么在蓝图中&#xff0c;我们如何调用呢&#xff1f;下面我们来一一讲解 通过函…

html+css+js网页制作 京东首页官网 ui还原度100%

htmlcssjs网页制作 京东首页官网 ui还原度100% 网页作品代码简单&#xff0c;可使用任意HTML编辑软件&#xff08;如&#xff1a;Dreamweaver、HBuilder、Vscode 、Sublime 、Webstorm、Text 、Notepad 等任意html编辑软件进行运行及修改编辑等操作&#xff09;。 获取源码 …

530系列变频器ACS530-01-363A-4可议价

530系列变频器ACS530-01-363A-4可议价 530系列变频器ACS530-01-363A-4可议价 530系列变频器ACS530-01-363A-4可议价 530系列变频器ACS530-01-363A-4引脚线 530系列变频器ACS530-01-363A-4说明书 530系列变频器ACS530-01-363A-4电路图 ACS530-01-363A-4变频器功率的选用 A…

融合创新:EasyCVR视频汇聚平台云计算技术与AI技术共筑雪亮工程智能防线

随着信息技术的飞速发展&#xff0c;视频云计算技术作为云计算领域的一个重要分支&#xff0c;正逐步在公共安全、社会治理等领域展现出其独特的优势。特别是在雪亮工程这一群众性治安防控工程中&#xff0c;视频云计算技术更是发挥了不可替代的作用。本文将从视频云计算技术的…

HarmonyOS开发案例:列表场景实例-TaskPool

介绍 本实例通过列表场景实例讲解&#xff0c;介绍在TaskPool线程中操作关系型数据库的方法&#xff0c;涵盖单条插入、批量插入、删除和查询操作。 效果图预览 使用说明 进入页面有insert(单条数据插入)、batch insert(批量数据插入)、query(查询操作)三个按钮&#xff0c;…

6.7分不降反升的IEEE trans:“江湖地位”超稳的1区,离TOP还有多远?

本周投稿推荐 SCI&EI • 1区计算机水刊&#xff0c;3.5-4.0&#xff08;48天录用&#xff09; • 2区-Top水刊&#xff0c;2.0-3.0&#xff08;沾边可录&#xff09; • 能源电力水刊&#xff0c;无版面费&#xff08;25天录用&#xff09; EI • 各领域沾边均可&…

PyTorch--残差网络(ResNet)在CIFAR-10数据集进行图像分类

完整代码 import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms# Device configuration device torch.device(cuda if torch.cuda.is_available() else cpu)# Hyper-parameters num_epochs 80 batch_size 100 learning_rate…

星地多网融合调度平台:高效融合,智慧救援

在应急救援领域&#xff0c;通信的畅通无阻是保障救援行动成功的关键。然而&#xff0c;面对复杂多变的救援环境和多样化的通信需求&#xff0c;传统的通信系统往往难以满足现代应急救援的高标准要求。为了克服这些挑战&#xff0c;星地多网融合调度平台应运而生&#xff0c;它…

【大模型理论篇】生成式模型算法原理深入浅出

1. 背景介绍 随着大模型的推出&#xff0c;“生成式AI”这个名词一夜之间席卷大江南北。甚至很多人的概念里&#xff0c;“生成式AI”等同于人工智能。但事实上&#xff0c;人工智能(Artificial Intelligence)涵盖的范围要广的多&#xff0c;生成式AI只是其中的一个部分&#x…

SpringBoot教程(二十一) | SpringBoot实现单点定时任务之@Scheduled

SpringBoot教程&#xff08;二十一&#xff09; | SpringBoot实现单点定时任务之Scheduled 前言巨坑&#xff08;Scheduled任务都用了同一个线程去执行&#xff0c;导致定时任务存在堵塞&#xff09;解决办法一&#xff1a;添加自定义的ThreadPoolTaskScheduler配置&#xff08…

html+css 实现hover 换背景跳动按钮

前言:哈喽,大家好,今天给大家分享html+css 实现hover 换背景跳动按钮!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、原理解析💡这个按钮hover后,有4个变化:📝1.1…

【C++二分查找】2080. 区间内查询数字的频率

本文涉及的基础知识点 C二分查找 LeetCode2080. 区间内查询数字的频率 请你设计一个数据结构&#xff0c;它能求出给定子数组内一个给定值的 频率 。 子数组中一个值的 频率 指的是这个子数组中这个值的出现次数。 请你实现 RangeFreqQuery 类&#xff1a; RangeFreqQuery(i…