当前位置: 首页 > 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; 困扰管理层的许多问题当中,宠物店管理也是不敢忽视的一块。但是管理好宠物店又面临很多麻烦需要解决,于是乎变得非常合乎时…...

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…...

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

Ubuntu系统下交叉编译openssl

一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机&#xff1a;Ubuntu 20.04.6 LTSHost&#xff1a;ARM32位交叉编译器&#xff1a;arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

【HTTP三个基础问题】

面试官您好&#xff01;HTTP是超文本传输协议&#xff0c;是互联网上客户端和服务器之间传输超文本数据&#xff08;比如文字、图片、音频、视频等&#xff09;的核心协议&#xff0c;当前互联网应用最广泛的版本是HTTP1.1&#xff0c;它基于经典的C/S模型&#xff0c;也就是客…...

网站指纹识别

网站指纹识别 网站的最基本组成&#xff1a;服务器&#xff08;操作系统&#xff09;、中间件&#xff08;web容器&#xff09;、脚本语言、数据厍 为什么要了解这些&#xff1f;举个例子&#xff1a;发现了一个文件读取漏洞&#xff0c;我们需要读/etc/passwd&#xff0c;如…...

基于Java+MySQL实现(GUI)客户管理系统

客户资料管理系统的设计与实现 第一章 需求分析 1.1 需求总体介绍 本项目为了方便维护客户信息为了方便维护客户信息&#xff0c;对客户进行统一管理&#xff0c;可以把所有客户信息录入系统&#xff0c;进行维护和统计功能。可通过文件的方式保存相关录入数据&#xff0c;对…...

redis和redission的区别

Redis 和 Redisson 是两个密切相关但又本质不同的技术&#xff0c;它们扮演着完全不同的角色&#xff1a; Redis: 内存数据库/数据结构存储 本质&#xff1a; 它是一个开源的、高性能的、基于内存的 键值存储数据库。它也可以将数据持久化到磁盘。 核心功能&#xff1a; 提供丰…...

Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解

文章目录 一、开启慢查询日志&#xff0c;定位耗时SQL1.1 查看慢查询日志是否开启1.2 临时开启慢查询日志1.3 永久开启慢查询日志1.4 分析慢查询日志 二、使用EXPLAIN分析SQL执行计划2.1 EXPLAIN的基本使用2.2 EXPLAIN分析案例2.3 根据EXPLAIN结果优化SQL 三、使用SHOW PROFILE…...

大数据治理的常见方式

大数据治理的常见方式 大数据治理是确保数据质量、安全性和可用性的系统性方法&#xff0c;以下是几种常见的治理方式&#xff1a; 1. 数据质量管理 核心方法&#xff1a; 数据校验&#xff1a;建立数据校验规则&#xff08;格式、范围、一致性等&#xff09;数据清洗&…...