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++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

C++11委托构造函数和继承构造函数的实现

《C++11委托构造函数和继承构造函数的实现》C++引入了委托构造函数和继承构造函数这两个重要的特性,本文主要介绍了C++11委托构造函数和继承构造函数的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、委托构造函数1.1 委托构造函数的定义与作用1.2 委托构造函数的语法1.3 委托构造函

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ