C++标准库之numeric

2023-10-12 09:21
文章标签 c++ 标准 numeric

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/194886

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、

使用C/C++调用libcurl调试消息的方式

《使用C/C++调用libcurl调试消息的方式》在使用C/C++调用libcurl进行HTTP请求时,有时我们需要查看请求的/应答消息的内容(包括请求头和请求体)以方便调试,libcurl提供了多种... 目录1. libcurl 调试工具简介2. 输出请求消息使用 CURLOPT_VERBOSE使用 C

C++实现获取本机MAC地址与IP地址

《C++实现获取本机MAC地址与IP地址》这篇文章主要为大家详细介绍了C++实现获取本机MAC地址与IP地址的两种方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 实际工作中,项目上常常需要获取本机的IP地址和MAC地址,在此使用两种方案获取1.MFC中获取IP和MAC地址获取