用新向量中的对应值替换向量中的所有奇数值

Lum*_*mpi 7 c++ algorithm vector stdvector c++11

给定以下向量:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
Run Code Online (Sandbox Code Playgroud)

最后,我想foo包含{ 10, 2, 30, 4, 50, 6, 70 }表示替换所有奇数的值。

我已经尝试过 std::replace_if 算法,但是如何访问条形对应的值?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
Run Code Online (Sandbox Code Playgroud)

眠りネ*_*ネロク 8

您可以使用std::transform带有两个输入迭代器范围的重载:

std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(),
  [](auto const& a, auto const& b) {
     if (a % 2)
        return b;
     return a; 
  }
);
Run Code Online (Sandbox Code Playgroud)