如何操作两个向量,并将结果保存到另一个向量

How to operate on two vectors and save the result to another vector

本文关键字:向量 结果 保存 另一个 两个 何操作 操作      更新时间:2023-10-16
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>());