如何逐个添加两个 STL 向量的元素?

How to add element by element of two STL vectors?(如何逐个添加两个 STL 向量的元素?)

本文介绍了如何逐个添加两个 STL 向量的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很愚蠢,但我需要以一种非常有效的方式来做——它将在我的代码中再次执行.我有一个返回向量的函数,我必须将返回的值逐个元素添加到另一个向量中.很简单:

The question is quite dumb, but I need to do it in a very efficient way - it will be performed over an over again in my code. I have a function that returns a vector, and I have to add the returned values to another vector, element by element. Quite simple:

vector<double> result;
vector<double> result_temp
for(int i=0; i< 10; i++) result_temp.push_back(i);

result += result_temp //I would like to do something like that.
for(int i =0; i< result_temp.size();i++)result[i] += result_temp[i]; //this give me segfault

我想做的数学运算是

u[i] = u[i] + v[i] 对于所有的 i

u[i] = u[i] + v[i] for all i

可以做什么?

谢谢

添加了一个简单的初始化,因为这不是重点.结果应该如何初始化?

added a simple initialization, as that is not the point. How should result be initialized?

推荐答案

如果您尝试将一个 vector 附加到另一个,您可以使用以下类似的方法.这些来自我的一个实用程序库 - std::vector 的两个 operator+= 重载:一个将单个元素附加到 vector,另一个附加整个vector:

If you are trying to append one vector to another, you can use something like the following. These are from one of my utilities libraries--two operator+= overloads for std::vector: one appends a single element to the vector, the other appends an entire vector:

template <typename T>
std::vector<T>& operator+=(std::vector<T>& a, const std::vector<T>& b)
{
    a.insert(a.end(), b.begin(), b.end());
    return a;
}

template <typename T>
std::vector<T>& operator+=(std::vector<T>& aVector, const T& aObject)
{
    aVector.push_back(aObject);
    return aVector;
}

如果您正在尝试执行求和(即,创建一个新的 vector 包含其他两个 vector 的元素之和),您可以使用一些东西像下面这样:

If you are trying to perform a summation (that is, create a new vector containing the sums of the elements of two other vectors), you can use something like the following:

#include <algorithm>
#include <functional>

template <typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
    assert(a.size() == b.size());

    std::vector<T> result;
    result.reserve(a.size());

    std::transform(a.begin(), a.end(), b.begin(), 
                   std::back_inserter(result), std::plus<T>());
    return result;
}

您可以类似地实现 operator+= 重载.

You could similarly implement an operator+= overload.

这篇关于如何逐个添加两个 STL 向量的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何逐个添加两个 STL 向量的元素?

基础教程推荐