C++标准库之numeric

一. 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;	// 输出55
    return 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;	// 输出3628800
    return 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;	// 输出 165
    return 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;    // 输出25
    return 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_difference

int 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 1
	std::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_product

int 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*3
	std::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_sum

int 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);//自定义操作myop
	std::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::iota

int 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值