当前位置: 首页 > 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

http://www.lryc.cn/news/189426.html

相关文章:

  • 第六章:最新版零基础学习 PYTHON 教程—Python 正则表达式(第二节 - Python 中的正则表达式与示例套装)
  • 【Python】WebUI自动化—Selenium的下载和安装、基本用法、项目实战(16)
  • c++视觉处理---图像重映射
  • 基于YOLO算法的单目相机2D测量(工件尺寸和物体尺寸)
  • Insight h2database 执行计划评估以及 Selectivity
  • [天翼杯 2021]esay_eval - RCE(disabled_function绕过||AS_Redis绕过)+反序列化(大小写wakeup绕过)
  • 基于SSM+Vue的在线作业管理系统的设计与实现
  • Webapck 解决:[webpack-cli] Error: Cannot find module ‘vue-loader/lib/plugin‘ 的问题
  • 使用UiPath和AA构建的解决方案 5. 使用UiPath ReFramework处理采购订单
  • SQL基本语法用例大全
  • MAX17058_MAX17059 STM32 iic 驱动设计
  • 大数据笔记-大数据处理流程
  • wps演示时图片任意位置拖动
  • NodeJs中使用JSONP和Cors实现跨域
  • Typora for Mac:优雅的Markdown文本编辑器,提升你的写作体验
  • STM32使用HAL库驱动TA6932数码管驱动芯片
  • day25--JS进阶(递归函数,深浅拷贝,异常处理,改变this指向,防抖及节流)
  • Python爬虫(二十三)_selenium案例:动态模拟页面点击
  • nodejs+vue宠物店管理系统
  • ceph版本和Ceph的CSI驱动程序
  • Android Studio Flutter真机调试错误
  • MQ - 41 容灾:跨地域、跨可用区的容灾和同步的方案设计
  • vue3学习(二)--- ref和reactive
  • 网络-HTTPS
  • GPU提升多分类问题
  • Selenium+Pytest自动化测试框架
  • 云原生Kubernetes:Rancher管理k8s集群
  • Java架构师异步架构设计
  • 电子书制作软件Vellum mac中文版特点
  • Langchain 代理 (Agents) ,赋能超级 LLMs