如何操作两个向量,并将结果保存到另一个向量
How to operate on two vectors and save the result to another vector
vector<int> vecIntsA{1, 2, 3, 4};
vector<int> vecIntsB{5, 6, 7, 8};
vector<int> vecIntsC(vecIntsA.size(), 0);
for(vector<int>::size_type i = 0; i < vecIntsA.size(); ++i)
{
vecIntsC[i] = vecIntsA[i] + vecIntsB[i];
}
问题>是否有一个STL算法,可以用来使这个计算在一行完成?
#include <algorithm>
#include <functional>
#include <vector>
std::vector<int> vecIntsA{1, 2, 3, 4};
std::vector<int> vecIntsB{5, 6, 7, 8};
std::vector<int> vecIntsC( vecIntsA.size(), 0)
std::transform( vecIntsA.begin(), vecIntsA.end(),
vecIntsB.begin(), vecIntsC.begin(), op);
其中op为二进制运算,std::plus<int>()
或自定义求和函数,如:
int sumInt( const int& a, const int& b)
{
return a + b;
}
在c++ 14中,您甚至可以删除任何显式提及的类型,而只使用std::plus<>()
:
std::transform( vecIntsA.begin(), vecIntsA.end(),
vecIntsB.begin(), vecIntsC.begin(), std::plus<>());
#include <algorithm>
#include <functional>
std::transform(vecInstA.begin(), vecInstA.end(),
vecInstB.begin(), vecInstC.begin(), std::plus<int>());
相关文章:
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- C++向量与 C# 列表.为什么它们会产生不同的结果?
- 提升精神:将结果复制到字符串向量中
- 在向量上声明缩减,在 1 个线程上运行给出的结果与没有 openmp 的结果不同
- 向量和 for 不产生结果
- 使用迭代器对向量的C 递归初始化产生不一致的结果
- 在不同类型的向量上使用 std::remove 的不同结果
- 将多个向量(函数结果)组合到一个使用模板中
- 在向量数组中获得前五个最大的结果
- C++:清除嵌套向量会导致奇怪的结果
- 根据标准对结构向量进行排序,然后显示结果
- 将std ::计数结果推入向量
- 调整OpenCV Mat向量向量的大小时出乎意料的结果
- 排序向量不断修改数据并打印不正确的结果
- 如何在不复制的情况下将过滤向量的结果存储在另一个向量中
- 将稀疏 mat-vec-mult 的结果存储到预分配的向量中
- 向量的最后一个成员在 Rcpp 中没有给出正确的结果
- 特征:如何将"greater than"的结果(在ArrayXf上)转换为特征向量
- 我正在制作一个简单的程序来计算向量结果,但我无法弄清楚为什么它不起作用。