当前位置: 首页 > news >正文

C++标准库之numeric

文章目录

  • 一. numeric库介绍
  • 二.详解
    • accumulate
      • 1. 计算数组中所有元素的和
      • 2. 计算数组中所有元素的乘积
      • 3. 计算数组中每个元素乘以3之后的和
      • 4.计算数组中每个元素减去3之后的和
      • 5.计算班级内学生的平均分
      • 6.拼接字符串
    • adjacent_difference
    • inner_product
    • partial_sum
    • iota
  • 三. 参考

一. numeric库介绍

numeric 是 C++ 标准库中的一个头文件,它提供了一组算法,用于对序列(包括数组、容器等)进行数学计算。这些算法包括求和、积、平均数、最大值、最小值等等,通常会被用在数值计算、统计学、信号处理等领域。

numeric库包含了多个函数,常用的函数包括:

  • std::accumulate:对序列中的所有元素求和
  • std::adjacent_difference:计算相邻元素之间的差值
  • std::inner_product:计算两个序列的内积
  • std::partial_sum:对序列进行累积和操作
  • std::iota:向序列中写入以val为初值的连续值序列

使用前需要引入相应的头文件:

#include <numeric>

二.详解

accumulate

accumulate(起始迭代器, 结束迭代器, 初始值, 自定义操作函数)

1. 计算数组中所有元素的和

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;int main() {vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = accumulate(arr.begin(), arr.end(), 0); // 初值0 + (1 + 2 + 3 + 4 +... + 10)cout << sum << endl;	// 输出55return 0;
}

2. 计算数组中所有元素的乘积

需要指定第四个参数,这里使用的是乘法函数 multiplies(), type根据元素的类型选择。

#include <iostream>
#include <vector>
#include <numeric>using namespace std;int main() {vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>()); // 初值1 * (1 * 2 * 3 * 4 *... * 10)cout << sum << endl;	// 输出3628800return 0;
}

3. 计算数组中每个元素乘以3之后的和

#include <iostream>
#include <vector>
#include <numeric>using namespace std;int fun(int acc, int num) {return acc + num * 3;     // 计算数组中每个元素乘以3
}int main() {vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = accumulate(arr.begin(), arr.end(), 0, fun);cout << sum << endl;	// 输出 165return 0;
}

4.计算数组中每个元素减去3之后的和

#include <iostream>
#include <vector>
#include <numeric>using namespace std;int fun(int acc, int num) {return acc + (num - 3) ;     // 计算数组中每个元素减去3之后的和
}int main() {vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = accumulate(arr.begin(), arr.end(), 0, fun);cout << sum << endl;    // 输出25return 0;
}

5.计算班级内学生的平均分

#include <iostream>
#include <vector>
#include <numeric>using namespace std;struct Student {string name;int score;Student() {};   // 无参构造函数Student(string name, int score) : name(name), score(score) {};  // 有参构造函数
};int fun(int acc, Student b) {return acc + b.score;
}int main() {vector<Student> arr;arr.emplace_back("Alice", 82);arr.emplace_back("Bob", 91);arr.emplace_back("Lucy", 85);arr.emplace_back("Anna", 60);arr.emplace_back("June", 73);int avg_score = accumulate(arr.begin(), arr.end(), 0, fun) / arr.size();	// 总分/学生数cout << avg_score << endl;return 0;
}

6.拼接字符串

C++中字符串之间也可以使用+,即拼接两个字符串。

#include <iostream>
#include <vector>
#include <numeric>using namespace std;int main() {vector<string> words{"this ", "is ", "a ", "sentence!"};string init, res;res = accumulate(words.begin(), words.end(), init);    // 连接字符串cout << res << endl;    // this is a sentence!return 0;
}

adjacent_difference

功能:对输入序列,计算相邻两项的差值(后一个减前一个元素),写入到输出序列(result)中。

函数模板

//模板一:默认形式,相邻差值写入至result中
template <class InputIterator, class OutputIterator>OutputIterator adjacent_difference (InputIterator first, InputIterator last,OutputIterator result);//模板二:自定义操作--binary_op
template <class InputIterator, class OutputIterator, class BinaryOperation>OutputIterator adjacent_difference ( InputIterator first, InputIterator last,OutputIterator result, BinaryOperation binary_op );

应用举例

#include <iostream>	  // std::cout
#include <functional> // std::multiplies
#include <numeric>	  // std::adjacent_differenceint myop(int x, int y) { return x + y; }int main()
{int val[] = {1, 2, 3, 5, 9, 11, 12};int result[7];std::adjacent_difference(val, val + 7, result);//后面减前面的:1 1 1 2 4 2 1std::cout << "using default adjacent_difference: ";for (int i = 0; i < 7; i++)std::cout << result[i] << ' ';std::cout << '\n';std::adjacent_difference(val, val + 7, result, std::multiplies<int>());//std::multiplies<int>():表示乘法std::cout << "using functional operation multiplies: ";for (int i = 0; i < 7; i++)std::cout << result[i] << ' ';std::cout << '\n';std::adjacent_difference(val, val + 7, result, myop);//自定义方法std::cout << "using custom function: ";for (int i = 0; i < 7; i++)std::cout << result[i] << ' ';std::cout << '\n';return 0;
}

输出:

using default adjacent_difference: 1 1 1 2 4 2 1 
using functional operation multiplies: 1 2 6 15 45 99 132 
using custom function: 1 3 5 8 14 20 23 

inner_product

功能:计算两个输入序列的内积。

函数模板

//模板一:默认模板
template <class InputIterator1, class InputIterator2, class T>T inner_product (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, T init);//模板二:自定义操作--binary_op1 binary_op2
template <class InputIterator1, class InputIterator2, class T,class BinaryOperation1, class BinaryOperation2>T inner_product (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, T init,BinaryOperation1 binary_op1,BinaryOperation2 binary_op2);

应用举例

#include <iostream>	  // std::cout
#include <functional> // std::minus, std::divides
#include <numeric>	  // std::inner_productint myaccumulator(int x, int y) { return x - y; }
int myproduct(int x, int y) { return x + y; }int main()
{int init = 100;int series1[] = {10, 20, 30};int series2[] = {1, 2, 3};std::cout << "using default inner_product: ";std::cout << std::inner_product(series1, series1 + 3, series2, init);//init = init + (*first1)*(*first2) ==》100 + 10*1 + 20*2 + 30*3std::cout << '\n';std::cout << "using functional operations: ";std::cout << std::inner_product(series1, series1 + 3, series2, init,std::minus<int>(), std::divides<int>());std::cout << '\n';std::cout << "using custom functions: ";std::cout << std::inner_product(series1, series1 + 3, series2, init,myaccumulator, myproduct);std::cout << '\n';return 0;
}

输出:

using default inner_product: 240
using functional operations: 70
using custom functions: 34

partial_sum

功能:计算局部累加和(每次都加上前面的所有元素),计算结果放入result中。

//模板一:默认计算计算局部累加和
template <class InputIterator, class OutputIterator>OutputIterator partial_sum (InputIterator first, InputIterator last,OutputIterator result);//模板二:自定义操作--binary_op
template <class InputIterator, class OutputIterator, class BinaryOperation>OutputIterator partial_sum (InputIterator first, InputIterator last,OutputIterator result, BinaryOperation binary_op);

应用举例

#include <iostream>	  // std::cout
#include <functional> // std::multiplies
#include <numeric>	  // std::partial_sumint myop(int x, int y) { return x + y + 1; }int main()
{int val[] = {1, 2, 3, 4, 5};int result[5];std::partial_sum(val, val + 5, result);//每次加入前面所有的元素放入result中std::cout << "using default partial_sum: ";for (int i = 0; i < 5; i++)std::cout << result[i] << ' ';std::cout << '\n';std::partial_sum(val, val + 5, result, std::multiplies<int>());//每次乘以前面的元素std::cout << "using functional operation multiplies: ";for (int i = 0; i < 5; i++)std::cout << result[i] << ' ';std::cout << '\n';std::partial_sum(val, val + 5, result, myop);//自定义操作myopstd::cout << "using custom function: ";for (int i = 0; i < 5; i++)std::cout << result[i] << ' ';std::cout << '\n';return 0;
}

输出:

using default partial_sum: 1 3 6 10 15 
using functional operation multiplies: 1 2 6 24 120 
using custom function: 1 4 8 13 19 

iota

功能:向序列中写入以val为初值的连续值序列。

函数模板

template <class ForwardIterator, class T>void iota (ForwardIterator first, ForwardIterator last, T val);

应用举例

#include <iostream> // std::cout
#include <numeric>	// std::iotaint main()
{int numbers[10];std::iota(numbers, numbers + 10, 100);//以100为初值for (int &i : numbers)std::cout << ' ' << i;std::cout << '\n';return 0;
}

输出:

100 101 102 103 104 105 106 107 108 109

三. 参考

https://blog.csdn.net/QLeelq/article/details/122548414
https://blog.csdn.net/VariatioZbw/article/details/125257536

相关文章:

C++标准库之numeric

文章目录 一. numeric库介绍二.详解accumulate1. 计算数组中所有元素的和2. 计算数组中所有元素的乘积3. 计算数组中每个元素乘以3之后的和4.计算数组中每个元素减去3之后的和5.计算班级内学生的平均分6.拼接字符串 adjacent_differenceinner_productpartial_sumiota 三. 参考 …...

第六章:最新版零基础学习 PYTHON 教程—Python 正则表达式(第二节 - Python 中的正则表达式与示例套装)

正则表达式 (RegEx)是一种特殊的字符序列,它使用搜索模式来查找字符串或字符串集。它可以通过将文本与特定模式进行匹配来检测文本是否存在,并且还可以将模式拆分为一个或多个子模式。Python 提供了一个re模块,支持在 Python 中使用正则表达式。它的主要功能是提供搜索,其中…...

【Python】WebUI自动化—Selenium的下载和安装、基本用法、项目实战(16)

文章目录 一.介绍二.下载安装selenium三.安装浏览器驱动四.QuickStart—自动访问百度五.Selenium基本用法1.定位节点1.1.单个元素定位1.2.多个元素定位 2.控制浏览器2.1.设置浏览器窗口大小、位置2.2.浏览器前进、刷新、后退、关闭3.3.等待3.4.Frame3.5.多窗口3.6.元素定位不到…...

c++视觉处理---图像重映射

图像重映射&#xff1a;cv::remap cv::remap 是OpenCV中的一个函数&#xff0c;用于执行图像重映射&#xff0c;允许您通过重新映射像素的位置来变换图像。这个函数非常有用&#xff0c;可以用于各种图像处理任务&#xff0c;如校正畸变、透视变换、几何变换等。 下面是 cv::…...

基于YOLO算法的单目相机2D测量(工件尺寸和物体尺寸)

1.简介 1.1 2D测量技术 基于单目相机的2D测量技术在许多领域中具有重要的背景和意义。 工业制造&#xff1a;在工业制造过程中&#xff0c;精确测量是确保产品质量和一致性的关键。基于单目相机的2D测量技术可以用于检测和测量零件尺寸、位置、形状等参数&#xff0c;进而实…...

Insight h2database 执行计划评估以及 Selectivity

生成执行计划是任何一个数据库不可缺少的过程。通过本文看执行计划生成原理。 最优的执行计划就是寻找最小计算成本的过程。 本文侧重 BTree 索引的成本计算的实现 以及 基础概念选择度的分析。 寻找最优执行计划 找到最佳的索引&#xff0c;实现最少的遍历&#xff0c;得到想要…...

[天翼杯 2021]esay_eval - RCE(disabled_function绕过||AS_Redis绕过)+反序列化(大小写wakeup绕过)

[天翼杯 2021]esay_eval 1 解题流程1.1 分析1.2 解题1.2.1 一阶段1.2.2 二阶段二、思考总结题目代码: <?php class A{public $code = "";...

基于SSM+Vue的在线作业管理系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用Vue技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…...

Webapck 解决:[webpack-cli] Error: Cannot find module ‘vue-loader/lib/plugin‘ 的问题

1、问题描述&#xff1a; 其一、报错为&#xff1a; [webpack-cli] Error: Cannot find module vue-loader/lib/plugin 中文为&#xff1a; [webpack-cli] 错误&#xff1a;找不到模块“vue-loader/lib/plugin” 其二、问题描述为&#xff1a; 在项目打包的时候 npm run …...

使用UiPath和AA构建的解决方案 5. 使用UiPath ReFramework处理采购订单

在本章中,我们将使用UiPath Robotic Enterprise Framework(简称ReFramework)创建自动化。ReFramework是一个快速构建强大的UiPath自动化的模板。它可以作为所有UiPath项目的起点。 模板可以满足您在任何自动化中的大部分核心需求——在配置文件中读取和存储数据,强大的异常…...

SQL基本语法用例大全

文章目录 SQL语法概述简单查询计算列查询条件查询范围查询使用逻辑运算符过滤数据使用IN操作符过滤数据格式化结果集模糊查询行数据过滤数据排序数据统计分析分组总计简单子查询多行子查询多表链接插入数据更新和删除数据使用视图数据库管理数据表管理 SQL语法概述 SQL(Struct…...

MAX17058_MAX17059 STM32 iic 驱动设计

本文采用资源下载链接&#xff0c;含完整工程代码 MAX17058-MAX17059STM32iic驱动设计内含有代码、详细设计过程文档&#xff0c;实际项目中使用代码&#xff0c;稳定可靠资源-CSDN文库 简介 MAX17058/MAX17059 IC是微小的锂离子(Li )在手持和便携式设备的电池电量计。MAX170…...

大数据笔记-大数据处理流程

大家对大数据处理流程大体上认识差不多&#xff0c;具体做起来可能细节各不相同&#xff0c;一幅简单的大数据处理流程图如下&#xff1a; 1&#xff09;数据采集&#xff1a;数据采集是大数据处理的第一步。 数据采集面对的数据来源是多种多样的&#xff0c;包括各种传感器、社…...

wps演示时图片任意位置拖动

wps演示时图片任意位置拖动 1.wps11.1版本&#xff0c;其他版本的宏插件可以自己下载。2.先确认自己的wps版本是不是11.13.检查是否有图像工具4.检查文件格式和安全5.开发工具--图像6.选中图像控件&#xff0c;右击选择查看代码&#xff0c;将原有代码删除&#xff0c;将下边代…...

NodeJs中使用JSONP和Cors实现跨域

跨域是为了解决浏览器请求域名&#xff0c;协议&#xff0c;端口不同的接口&#xff0c;相同的接口是不需要实现跨域的。 1.使用JSONP格式实现跨域 实现步骤 动态创建一个script标签 src指向接口的地址 定义一个函数和后端调用的函数名一样 实现代码 -- 在nodejs中使用http内…...

Typora for Mac:优雅的Markdown文本编辑器,提升你的写作体验

Typora是一款强大的Markdown文本编辑器&#xff0c;专为Mac用户设计。无论你是写作爱好者&#xff0c;还是专业作家或博客作者&#xff0c;Typora都能为你提供无与伦比的写作体验。 1. 直观的界面设计 Typora的界面简洁明了&#xff0c;让你专注于写作&#xff0c;而不是被复…...

STM32使用HAL库驱动TA6932数码管驱动芯片

TA6932介绍 8段16位&#xff0c;支持共阴共阳LED数码管。 2、STM32CUBEMX配置引脚 推挽配置即可。 3、头文件 /******************************************************************************************** * TA6932&#xff1a;8段16位数码管驱动 *******************…...

day25--JS进阶(递归函数,深浅拷贝,异常处理,改变this指向,防抖及节流)

目录 浅拷贝 1.拷贝对象①Object.assgin() ②展开运算符newObj {...obj}拷贝对象 2.拷贝数组 ①Array.prototype.concat() ② newArr [...arr] 深拷贝 1.通过递归实现深拷贝 2.lodash/cloneDeep实现 3.通过JSON.stringify()实现 异常处理 throw抛异常 try/catch捕获…...

Python爬虫(二十三)_selenium案例:动态模拟页面点击

本篇主要介绍使用selenium模拟点击下一页&#xff0c;更多内容请参考:Python学习指南 #-*- coding:utf-8 -*-import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import timeclass douyuSelenium…...

nodejs+vue宠物店管理系统

例如&#xff1a;如何在工作琐碎,记录繁多的情况下将宠物店管理的当前情况反应给管理员决策,等等。在此情况下开发一款宠物店管理系统小程序&#xff0c; 困扰管理层的许多问题当中,宠物店管理也是不敢忽视的一块。但是管理好宠物店又面临很多麻烦需要解决,于是乎变得非常合乎时…...

web vue 项目 Docker化部署

Web 项目 Docker 化部署详细教程 目录 Web 项目 Docker 化部署概述Dockerfile 详解 构建阶段生产阶段 构建和运行 Docker 镜像 1. Web 项目 Docker 化部署概述 Docker 化部署的主要步骤分为以下几个阶段&#xff1a; 构建阶段&#xff08;Build Stage&#xff09;&#xff1a…...

conda相比python好处

Conda 作为 Python 的环境和包管理工具&#xff0c;相比原生 Python 生态&#xff08;如 pip 虚拟环境&#xff09;有许多独特优势&#xff0c;尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处&#xff1a; 一、一站式环境管理&#xff1a…...

【网络安全产品大调研系列】2. 体验漏洞扫描

前言 2023 年漏洞扫描服务市场规模预计为 3.06&#xff08;十亿美元&#xff09;。漏洞扫描服务市场行业预计将从 2024 年的 3.48&#xff08;十亿美元&#xff09;增长到 2032 年的 9.54&#xff08;十亿美元&#xff09;。预测期内漏洞扫描服务市场 CAGR&#xff08;增长率&…...

基于当前项目通过npm包形式暴露公共组件

1.package.sjon文件配置 其中xh-flowable就是暴露出去的npm包名 2.创建tpyes文件夹&#xff0c;并新增内容 3.创建package文件夹...

C++ 基础特性深度解析

目录 引言 一、命名空间&#xff08;namespace&#xff09; C 中的命名空间​ 与 C 语言的对比​ 二、缺省参数​ C 中的缺省参数​ 与 C 语言的对比​ 三、引用&#xff08;reference&#xff09;​ C 中的引用​ 与 C 语言的对比​ 四、inline&#xff08;内联函数…...

搭建DNS域名解析服务器(正向解析资源文件)

正向解析资源文件 1&#xff09;准备工作 服务端及客户端都关闭安全软件 [rootlocalhost ~]# systemctl stop firewalld [rootlocalhost ~]# setenforce 0 2&#xff09;服务端安装软件&#xff1a;bind 1.配置yum源 [rootlocalhost ~]# cat /etc/yum.repos.d/base.repo [Base…...

Rust 开发环境搭建

环境搭建 1、开发工具RustRover 或者vs code 2、Cygwin64 安装 https://cygwin.com/install.html 在工具终端执行&#xff1a; rustup toolchain install stable-x86_64-pc-windows-gnu rustup default stable-x86_64-pc-windows-gnu ​ 2、Hello World fn main() { println…...

uniapp 小程序 学习(一)

利用Hbuilder 创建项目 运行到内置浏览器看效果 下载微信小程序 安装到Hbuilder 下载地址 &#xff1a;开发者工具默认安装 设置服务端口号 在Hbuilder中设置微信小程序 配置 找到运行设置&#xff0c;将微信开发者工具放入到Hbuilder中&#xff0c; 打开后出现 如下 bug 解…...

消防一体化安全管控平台:构建消防“一张图”和APP统一管理

在城市的某个角落&#xff0c;一场突如其来的火灾打破了平静。熊熊烈火迅速蔓延&#xff0c;滚滚浓烟弥漫开来&#xff0c;周围群众的生命财产安全受到严重威胁。就在这千钧一发之际&#xff0c;消防救援队伍迅速行动&#xff0c;而豪越科技消防一体化安全管控平台构建的消防“…...

软件工程 期末复习

瀑布模型&#xff1a;计划 螺旋模型&#xff1a;风险低 原型模型: 用户反馈 喷泉模型:代码复用 高内聚 低耦合&#xff1a;模块内部功能紧密 模块之间依赖程度小 高内聚&#xff1a;指的是一个模块内部的功能应该紧密相关。换句话说&#xff0c;一个模块应当只实现单一的功能…...