c++ - 用新 vector 中的对应值替换 vector 中的所有奇数值

标签 c++ algorithm c++11 vector stdvector

给定以下 vector :

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

最后我要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

最佳答案

您可以使用 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; 
  }
);

关于c++ - 用新 vector 中的对应值替换 vector 中的所有奇数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60299684/

相关文章:

algorithm - CRF中的前向和前向后向算法

java - 如何计算多个字符串中某个字符出现的次数?

c++ - 如何将使用#ifdef编写的支持多种平台的代码移动到库函数中?

c++ - 在 C++11 中,原始字符串文字可以有多行吗?

c++ - gdb 列表错误 "No such file or directory"

c++ - 最小的 3 个整数并打印组中最小的数字

c++ - OpenCV绘制带有轴标签和坐标的直方图

c++ - 如何使用 qteSTLib 测试完整的 Qt5 GUI?

algorithm - 纯 Knuth/Fisher-Yates 在 haskell 中洗牌

c++ - Lambda 作为模板函数