小编Lum*_*mpi的帖子

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

给定以下向量:

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 …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm vector stdvector c++11

7
推荐指数
1
解决办法
290
查看次数

标签 统计

algorithm ×1

c++ ×1

c++11 ×1

stdvector ×1

vector ×1