将两个int向量的元素相互平行求和

时间:2017-10-21 03:45:55

标签: c++ vector int add

我正在尝试获取两个向量的每个元素的总和,并将总数推送到新的向量。

即。

a = {1,2,3}& b = {1,2,3}

c = a + b

c = {2,4,6}

我已经让它适用于相同大小的矢量,但只要其中一个矢量大于另一个矢量,我就会得到一个矢量下标超出范围误差。

a = {1,2,3}& b = {1,2,3,4}

c = a + b

我假设这发生在b [3] + ??期间,我将如何添加它,以便输出:

c = {2,4,6,4}

到目前为止我得到的是:

vector<int> a = { 1,2,3,4 };
vector<int> b = { 5,4,3,2,1 };

vector<int> *vPtr;
vPtr = new vector<int>;

int sum;
int size = a.size();
if (size < b.size())
    size = b.size();

for (unsigned i = 0; i < size; i++) {
    sum = a[i] + b[i];
    (*vPtr).push_back(sum);
}

for (vector<int>::const_iterator it = (*vPtr).begin(); it != (*vPtr).end(); it++)
    cout << *it << " ";

cout << endl;

return 0;

3 个答案:

答案 0 :(得分:1)

在末尾填充带有额外零的较小向量。这是一个例子:

int sizeDifference = abs(a.size() - b.size());
if(sizeDifference != 0){
  if(a.size() > b.size())
    for(int i = 0; i<sizeDifference; ++i)
      b.push_back(0);
  else
    for(int i = 0; i<sizeDifference; ++i)
      a.push_back(0);
}

答案 1 :(得分:1)

通常我用迭代器分三部分来做这件事。两个向量具有共同元素的部分。 a部分b超过b且部分{/ 1}}的部分长于a

std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6, 7};
std::vector<int> c;

// reserve enough space for the longest vector
c.reserve(std::max(a.size(), b.size()));

auto a_itr = std::begin(a);
auto b_itr = std::begin(b);

// for the part where the positions coincide
for(; a_itr != std::end(a) && b_itr != std::end(b); ++a_itr, ++b_itr)
    c.push_back(*a_itr + *b_itr);

// for the part where a is longer than b (if any)
c.insert(std::end(c), a_itr, std::end(a));

// for the part where b is longer than a (if any)
c.insert(std::end(c), b_itr, std::end(b));

for(auto i: c)
    std::cout << i << '\n';

答案 2 :(得分:0)

size_type sm_size, lg_size;
vector<int> *lg_vec_ptr;
if (a.size < b.size()) {
   sm_size = a.size();
   lg_size = b.size();
   lg_vector_ptr = &b;
} else {
   sm_size = b.size();
   lg_size = a.size();
   lg_vector_ptr = &a;
}

vector<int> *sum_vec_ptr = new vector<int>;
size_type i;
for (i=0; i<sm_size; ++i)
    sum_vec_ptr->push_back( a[i] + b[i] );
for (   ; i<lg_size; ++i)
    sum_vec_ptr->push_back( lg_vector_ptr->[i] );

此方法不会修改原始矢量。