2个向量的总和值 [英] Sum values of 2 vectors
本文介绍了2个向量的总和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C++ 库中是否有任何实现的方法可以让您对两个向量(当然大小和类型相同)的值求和?
例如:
Is there any implemented method in the C++ library which allows you to sum the values of two vectors (of the same size and type of course)?
For example:
std::vector<int> a;//looks like this: 2,0,1,5,0
std::vector<int> b;//looks like this: 0,0,1,3,5
现在将它们的值相加应该如下所示:
Now then adding their values together should look like this:
//2,0,2,8,5
我期待的答案是不,没有"或是"+ 方法.
The answer I'm expecting is either "No there isn't" or "yes" + method.
推荐答案
您可以使用 std::transform
和 std::plus
std::vector<int> a;//looks like this: 2,0,1,5,0
std::vector<int> b;//looks like this: 0,0,1,3,5
// std::plus adds together its two arguments:
std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
// a = 2,0,2,8,5
这种形式的 std::transform
有 5 个参数:
This form of std::transform
takes 5 arguments:
- 前两个是第一个序列的初始位置和最终位置的输入迭代器.
- 第三个是到第二个范围的初始位置的输入迭代器.
- 第四个是存储操作结果的范围的初始位置的输出迭代器.
- 最后一个参数是一个二元函数,它接受两个元素作为参数(两个序列中的每一个),并返回一些可转换为 OutputIterator 指向的类型的结果值.
这篇关于2个向量的总和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文