【问题标题】:Summing the elements of two int vectors parallel to each other将两个相互平行的 int 向量的元素相加
【发布时间】:2018-04-02 06:12:57
【问题描述】:

我正在尝试获取两个向量的每个元素的总和并将总和推入一个新向量。

即。

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;

【问题讨论】:

  • 在较小的向量末尾用额外的零填充
  • 拿出一张空白纸。用简短、简明、简洁的英语陈述写下实现你正在尝试做的事情的逻辑逐步算法。之后,schedule an appointment with your rubber duck。在您的橡皮鸭批准您提出的解决方案后,只需将您写下的内容直接翻译成 C++。任务完成。

标签: c++ vector int add


【解决方案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);
}

【讨论】:

  • 啊,有道理。谢谢!
【解决方案2】:
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] );

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

【讨论】:

    【解决方案3】:

    通常我用迭代器分三部分来做这件事。两个向量具有共同元素的部分。 if/where a 部分比b 长,if/where b 部分比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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多